Java 将历元值转换为12小时格式的时间戳
我试图在Scala中将历元时间转换为时间戳 时代价值:1475596740 时间戳:1475596740*1000=>1475596740000 结果时间戳总是以24小时格式给出结果Java 将历元值转换为12小时格式的时间戳,java,scala,epoch,Java,Scala,Epoch,我试图在Scala中将历元时间转换为时间戳 时代价值:1475596740 时间戳:1475596740*1000=>1475596740000 结果时间戳总是以24小时格式给出结果 val outputformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa"); val formatteddTS = outputformat.format(ts) println(outputformat.parse(formattedd
val outputformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
val formatteddTS = outputformat.format(ts)
println(outputformat.parse(formatteddTS).getTime)
我需要将这个结果与另一个12小时格式的时间戳值进行比较。如果我做比较,结果是有线的
时间1(历元)
2016-10-04 21:29:00.0
1475596740000(毫秒)
时间2(12小时格式的时间戳)
2016-10-04 09:29:28.0
1475553568000(毫秒)
结果
time2-time1=>-43172
从逻辑上讲,2016-10-04 21:29:00.0和2016-10-04 09:29:28.0之间的时差约为28秒(28000),但我得到的结果是43172,我相信您的计算有问题,因为我可以通过您提供的数据看到正确的结果
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
long time1 = 1475596740000l;
long time2 = 1475553568000l;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
cal1.setTimeInMillis(time1);
System.out.println(dateFormat.format(cal1.getTime()));
cal2.setTimeInMillis(time2);
System.out.println(dateFormat.format(cal2.getTime()));
System.out.println(time1 - time2);
以及输出:
2016-10-04 10:59:00 PM
2016-10-04 10:59:28 AM
43172000
43172000是12小时左右,因为它应该是
编辑
好的,我用了你建议的另一种方法,结果还是一样的——43172000:
String date1 = "2016-10-04 21:29:00";
String date2 = "2016-10-04 09:29:28 AM";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa", Locale.ENGLISH);
Date dateObj1 = null;
Date dateObj2 = null;
try {
dateObj1 = format1.parse(date1);
dateObj2 = format2.parse(date2);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(dateObj1.getTime() - dateObj2.getTime());
而“2016-10-04 09:29:28 PM”则返回-28000。我认为问题出在日期转换的某个地方你应该在12小时格式的末尾看到
AM
或PM
。是的,这正在发生。但如果我将其转换为毫秒,则值保持不变。那么你是说不希望它们相同。@mhasan从逻辑上讲,2016-10-04 21:29:00.0和2016-10-04 09:29:28.0之间的时差约为28秒(28000),但我得到的结果是4317212016-10-04 21:29:00.0,2016-10-04 09:29:28.0将此字符串转换为date和getTime(),并进行差异处理。那么你就明白我的意思了。从逻辑上讲,2016-10-04 21:29:00.0和2016-10-04 09:29:28.0之间的时差大约是28秒(28000),但我得到的结果是43172