How to Format Date and Time in Android

How to format date and time in Android?

Use the standard Java DateFormat class.

For example to display the current date and time do the following:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

You can initialise a Date object with your own values, however you should be aware that the constructors have been deprecated and you should really be using a Java Calendar object.

How to convert Date to a particular format in android?

This is modified code that you should use:

String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);

Use hh for hours in order to get correct time.

Java 8 and later

Java 8 introduced new classes for time manipulation, so use following code in such cases:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));

Use h for hour format, since in this case hour has only one digit.

How do I change date time format in Android?

Here is working code

public String parseDateToddMMyyyy(String time) {
String inputPattern = "yyyy-MM-dd HH:mm:ss";
String outputPattern = "dd-MMM-yyyy h:mm a";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

Date date = null;
String str = null;

try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}

Documentation: SimpleDateFormat | Android Developers

How to get current time and date in Android

You could use:

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();

There are plenty of constants in Calendar for everything you need.

Check the Calendar class documentation.

Android - Converting current date and time with timezone

tl;dr

Use java.time classes.

OffsetDateTime            // Represent a moment as a date, a time-of-day, and an offset-from-UTC (a number of hours, minutes, seconds) with a resolution as fine as nanoseconds.
.now( // Capture the current moment.
ZoneOffset.UTC. // Specify your desired offset-from-UTC. Here we use an offset of zero, UTC itself, predefined as a constant.
) // Returns a `OffsetDateTime` object.
.format( // Generate text in a `String` object representing the date-time value of this `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US )
) // Returns a `String` object.

2018-09-27T05:39:41.023987+00:00

Or, use Z for UTC.

Instant.now().toString()

2018-09-27T05:39:41.023987Z

java.time

The modern approach uses the java.time that supplanted the terrible old date-time classes.

Specifically:

  • Use Instant or OffsetDateTime instead of java.util.Date.
  • Use DateTimeFormatter instead of `SimpleDateFormat.

Get the current time in UTC. We use the OffsetDateTime class rather than Instant for more flexible formatting when generating text.

ZoneOffset offset = ZoneOffset.UTC;
OffsetDateTime odt = OffsetDateTime.now( offset );

Define a formatting pattern to match your desired output. Note that the built-in formatting patterns use Z as standard shorthand for +00:00. The Z means UTC and is pronounced “Zulu”. This Zulu time format is quite common. I suggest using such formats with Z. But you asked explicitly for the long version of an offset-from-UTC of zero, so we must use a custom DateTimeFormatter object.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US );
String output = odt.format( f );

2018-09-27T05:39:41.023987+00:00

FYI, the formats discussed here comply with the ISO 8601 standard.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7

    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Android date format with Month

The easiest way to do this is to use a switch case

String monthStr = "";

switch(month) {
case 1:
monthStr = "January";
break;
case 2:
monthStr = "February";
break;
// and else
}

String dateLong = monthStr + "/" + day+ "/" + year;

Convert time value to format “hh:mm Am/Pm” using Android

I got answer just doing like this.

startTime = "2013-02-27 21:06:30";
StringTokenizer tk = new StringTokenizer(startTime);
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) {
e.printStackTrace();
}

Android - change Date format to - dd.mm.yyyy HH:mm

At First Post Your Code .

Please follow How do you format date and time in Android

Code for SimpleDateFormat . Just check the logic .

SimpleDateFormat timeStampFormat = new SimpleDateFormat("dd-yyyy-MM HHmm");
Date GetDate = new Date();
String DateStr = timeStampFormat.format(GetDate);

Now replace - as .

DateStr = DateStr.replace("-", ".");

how to convert date and time to 12 hour format

You need two formats: one to parse, and one to format. You need to parse from String to Date with one DateFormat, then format that Date into a String with the other format.

Currently, your single SimpleDateFormat is half way between - you've got HH which is 24-hour, but you've also got aa which is for am/pm. You want HH without the aa for input, and hh with the aa for output. (It's almost never appropriate to have both HH and aa.)

TimeZone utc = TimeZone.getTimeZone("etc/UTC");
DateFormat inputFormat = new SimpleDateFormat("dd MMM, yyyy HH:mm",
Locale.US);
inputFormat.setTimeZone(utc);
DateFormat outputFormat = new SimpleDateFormat("dd MMM, yyyy hh:mm aa",
Locale.US);
outputFormat.setTimeZone(utc);

Date date = inputFormat.parse(input);
String output = outputFormat.format(date);

Note that I'm setting the locale to US so it can always parse "Nov", and the time zone to UTC so you don't need to worry about certain times being skipped or ambiguous.



Related Topics



Leave a reply



Submit