Android: How to Format Date and Time Strings corre

2019-09-06 20:47发布

问题:

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();

回答1:

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



回答2:

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);



回答3:

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?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 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
    • Much 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….

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.



回答4:

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 + ".";
}


回答5:

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