简体   繁体   English

从java中的SimpleDateFormat中检索两个相等的日期

[英]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. date1date2以秒为单位表示,所以我期望输出中有两个不同的日期,但日期打印相同。 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. 两个时间戳之间的差异恰好是12个小时。

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. SimpleDateFormath标识符以AM / PM(1-12)格式化小时,因此您实际上不输出实际差异:日期从AM转移到PM。

Try with the k or H identifier which formats the hour in day as (1-24) or (0-23). 尝试使用kH标识符将日期中的小时格式化为(1-24)或(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: 你也可以输出的AM / PM标记与a标识符是这样的:

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. 这是因为您的日期是12小时appart,您使用小写'h'进行小时格式化。 The dates are 1am and 1pm, respectively. 日期分别是凌晨1点和1点。 In order to see this in your output use upper case 'H' or add 'a' to the format for the 'am/pm' marker. 为了在输出中看到这个,请使用大写“H”或将“a”添加到“am / pm”标记的格式中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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