How to display only current time using DateFormat.getDateTimeInstance() in android
Asked Answered
W

6

6

I am new to android. In android I want to display only current time in a textview in the format hh:mm am/pm (eg: 3:02 PM) I use the following code.

String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()); tv.setText(currentDateTimeString);

It gives the current date,month,year and time.But i need to get only the current time from this. Is there any way to display only time? Can anyone help me to get the time without date from the above code.[using DateFormat.getDateTimeInstance()]

Weathercock answered 26/11, 2013 at 9:10 Comment(1)
do u want to display current time into text view or edit text?Sib
M
9

try following code

     Date d=new Date();
     SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
     String currentDateTimeString = sdf.format(d);
     tv.setText(currentDateTimeString);
Michelsen answered 26/11, 2013 at 9:20 Comment(2)
Is this 24hr time or 12hr?Angel
12 hr... that's why I used 'a' for am/pmMichelsen
L
7

It gives the current date, month, year and time, but I need to get only the current time from this.

If you want to do this and respect the users preferences (e.g. 12 vs 24 hour clock) then continue to use DateFormat, only like so:

DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
Litigation answered 21/3, 2014 at 12:52 Comment(3)
Sorry, I've downvoted this answer by mistake. Actually, it's the only correct answer.Groome
@Groome thanks, I've edited so you should be able to remove downvote or upvote now.Litigation
This should be the accepted answer! Thanks for sharing.Tressatressia
E
1

try this:

<DigitalClock
        android:id="@+id/digitalClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DigitalClock" />

this is basic control of android.

Evangelina answered 26/11, 2013 at 9:20 Comment(0)
F
0
 startTime = ""+System.currentTimeMillis();
                    StringTokenizer tk = new StringTokenizer(startTime.trim());
                    String date = tk.nextToken();  
                    String time = tk.nextToken();

                    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
                    SimpleDateFormat sdfs = new SimpleDateFormat("hh:mm a");
                    Date dt;
                    try {    
                        dt = sdf.parse(time);
                        System.out.println("Time Display: " + sdfs.format(dt)); // <-- I got result here
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
Flay answered 26/11, 2013 at 9:15 Comment(0)
S
0
System.out.println(new SimpleDateFormat("HH:mm:SS").format(new Date()));

Android Time picker component follow the link http://developer.android.com/guide/topics/ui/controls/pickers.html

for more info

http://developer.android.com/reference/java/text/SimpleDateFormat.html

Sib answered 26/11, 2013 at 9:25 Comment(0)
F
0

It gives the current date,month,year and time.But i need to get only the current time from this.

The java.util.Date object is not a real Date-Time object like the modern Date-Time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the Date-Time in the JVM's timezone, calculated from this milliseconds value. If you need to print the Date-Time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it e.g.

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(sdf.format(date));

In order to get just the time, you just need to replace (a) yyyy-MM-dd'T'HH:mm:ss.SSSXXX with hh:mm a and (b) America/New_York with the applicable timezone.

However, the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern API:

import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Replace JVM's timezone i.e. ZoneId.systemDefault() with the applicable
        // timezone e.g. ZoneId.of("Europe/London")
        LocalTime time = LocalTime.now(ZoneId.systemDefault());

        // Print the default format i.e. the value of time.toString()
        System.out.println(time);

        // Custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
        String formattedTime = dtf.format(time); // Alternatively, time.format(dtf)
        System.out.println(formattedTime);
    }
}

Output:

11:59:07.443868
11:59 AM

Learn more about java.time, the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Faeroese answered 29/5, 2021 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.