简体   繁体   中英

Retrieve two equal dates from SimpleDateFormat in java

I made this snippet to show my problem:

import java.text.SimpleDateFormat;

public class Foo {
    public static void main(String[] args) {

        SimpleDateFormat formatter = new SimpleDateFormat("mm hh dd MM yyyy");
        String date1 = "1412293500";
        String date2 = "1412336700";
        String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
        String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
        System.out.println(dateString1 + " " + dateString2);

    }
}

date1 and date2 are expressed in seconds, so I'm expecting two different dates in output, but the dates are printed the same. I checked inside this online tool , and as you can see the dates are related to two different days.

How can I solve this?

The difference between your two timestamps is exactly 12 hours.

The h identifier in SimpleDateFormat formats the hours in AM/PM (1-12), so you actually do not output the real difference: the date was shifted from AM to PM.

Try with the k or H identifier which formats the hour in day as (1-24) or (0-23).

SimpleDateFormat formatter = new SimpleDateFormat("mm kk dd MM yyyy");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2); // prints 45 01 03 10 2014 45 13 03 10 2014

You could also output the AM/PM marker with the a identifier like this:

SimpleDateFormat formatter = new SimpleDateFormat("mm hh dd MM yyyy aa");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2); // prints 45 01 03 10 2014 AM 45 01 03 10 2014 PM

This is because your dates are 12h appart and you use the lower case 'h' for the hour formatting. The dates are 1am and 1pm, respectively. In order to see this in your output use upper case 'H' or add 'a' to the format for the 'am/pm' marker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM