Guy West
Guy West

Reputation: 424

Android: How to Format Date and Time Strings correctly?

How should I correctly format Date and Time Strings for the Android platform?

Here is some code:

String path = getFilesDir().getPath();
String filePath = path + "/somefile.xml";
File file = new File(filePath);
Date lastModDate = new Date(file.lastModified());
String filelastModDate = "Updated: " + lastModDate.toString();

Upvotes: 0

Views: 1744

Answers (6)

Aminul Haque Aome
Aminul Haque Aome

Reputation: 2589

Though, The question is very old, but it may help one who wants it Kotlin version of this answer. Here I take a empty file name DateUtil and create a function called getDateString() which has 3 arguments.

1st argument : Your input date
2nd argument : Your input date pattern
3rd argument : Your wanted date pattern

DateUtil.kt

object DatePattern {
    const val YEAR_MONTH_DAY = "yyyy-MM-dd"
    const val DAY_MONTH_YEAR = "dd-MM-yyyy"
    const val RFC3339 = "yyyy-MM-dd'T'HH:mm:ss'Z'"
}

fun getDateString(date: String, inputDatePattern: String, outputDatePattern: String): String {
    return try {
        val inputFormat = SimpleDateFormat(inputDatePattern, getDefault())
        val outputFormat = SimpleDateFormat(outputDatePattern, getDefault())

        outputFormat.format(inputFormat.parse(date))
    } catch (e: Exception) {
        ""
    }
}

And now use this method in your activity/fuction/dataSourse Mapper to get Date in String format like this

getDate("2022-01-18T14:41:52Z", RFC3339, DAY_MONTH_YEAR)

and output will be like this

18-01-2022

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 338181

tl;dr

Instant.ofEpochMilli(    // Parse milliseconds count to a moment in UTC.
    file.lastModified()  // A count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
)                        // Returns a `Instant` object.
.atZone(                 // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
    ZoneId.of( "Africa/Tunis" )
)                        // Returns a `ZonedDateTime` object.
.format(                 // Generate a `String`.
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.FULL )  // Specify how long or abbreviated.
    .withLocale( Locale.JAPAN )  // Specify a `Local` to determine human language and cultural norms used in localizing.
)                        // Returns a `String`. 

java.time

The modern approach uses the java.time classes.

The File.lastModified method returns a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.

long millisSinceEpoch = file.lastModified() ;

Parse that number as a modern java.time object.

Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;

Generate a String to represent that values using standard ISO 8601 format.

String output = instant.toString() ;  // Generate a `String` in standard ISO 8601 format.

2018-07-16T22:40:39.937Z

To view the same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

2018-07-17T10:40:39.937+12:00[Pacific/Auckland]

Let java.time automatically localize. To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine:
    • The human language for translation of name of day, name of month, and such.
    • The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Example:

Locale l = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );

mardi 17 juillet 2018 à 10:40:39 heure normale de la Nouvelle-Zélande


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?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 1

Basil Bourque
Basil Bourque

Reputation: 338181

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

Joda-Time

Install third-party library, Joda-Time.

By default, Joda-Time outputs strings in ISO 8601 format. That format is intuitively understandable by virtually anybody worldwide.

Search StackOverflow.com for many more examples.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;

DateTime now = new DateTime();
System.out.println( now );

When run…

2013-12-05T19:55:43.897-08:00

Upvotes: 0

Gunnar Bernstein
Gunnar Bernstein

Reputation: 6222

I would like to add my share here.

Note that the user can set his preferred format in the settings. Example on how to retrieve:

static DateFormat getUserDateFormat(Context context) {
    if (mUserDateFormat == null)
        mUserDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
    return mUserDateFormat;
}

See also ...getTimeFormat

You then have a java DateFormat to use with above mentioned examples.

Furthermore, Android contains it's own TextFormat class, look here: http://developer.android.com/reference/android/text/format/package-summary.html

This may look like:

static String getAppExpiredString() {
    String date = android.text.format.DateFormat.getDateFormat(getAppContext()).format(App_Main.APP_RUN_TILL.getTime());
    return getAppContext().getString(R.string.app_expired) + " " + date + ".";
}

Upvotes: 0

Guy West
Guy West

Reputation: 424

Thanks @receme I solved it. like this:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a",Locale.getDefault());
String currentTime = sdf.format(date);
Log.i(LOGTAG,"Current Time: " + currentTime);

Upvotes: 1

Md. Tahmid Mozaffar
Md. Tahmid Mozaffar

Reputation: 1005

You can format it various way...

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String currentTime = sdf.format(date);

Here you can put other format like

k:mm

h:mm

h:mm dd/MM/yyyy
etc.....

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

Upvotes: 4

Related Questions