简体   繁体   English

以特定格式将毫秒转换为日期

[英]Convert milliseconds to Date in specific format

Using below code , the output is 15-Mar-2016 06:24:41.296PM使用以下代码,输出为15-Mar-2016 06:24:41.296PM

Date sDate=new Date();
SimpleDateFormat pattern = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss.SSSa");
System.out.println(pattern .format(sDate));

If I want the output as 15-Mar-2016 06:00:00.0PM is it possible?如果我想要输出为15-Mar-2016 06:00:00.0PM可以吗?

Rather than using a Calendar and resetting portions of the date to zero, you can use single quotes to insert literal strings in the formatted date:您可以使用单引号在格式化的日期中插入文字字符串,而不是使用Calendar并将日期的部分重置为零:

SimpleDateFormat pattern = new SimpleDateFormat("dd-MMM-yyyy hh:'00:00.0'a");

Demo演示

Depending on whether you want to truncate (ie, floor) or round to the nearest hour, you could do one of the following:根据您是要截断(即,地板)还是四舍五入到最接近的小时,您可以执行以下操作之一:

    final long MS_PER_HOUR = 1000L * 60 * 60;
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss.SSSa");

    long now = System.currentTimeMillis();
    long trunc = (now / MS_PER_HOUR) * MS_PER_HOUR;
    long round = ((now + MS_PER_HOUR / 2) / MS_PER_HOUR) * MS_PER_HOUR;

    System.out.println("now:   " + fmt.format(new Date(now)));
    System.out.println("trunc: " + fmt.format(new Date(trunc)));
    System.out.println("round: " + fmt.format(new Date(round)));

Which will generate this output for a time between 09:00:00 and 09:29:59这将在 09:00:00 和 09:29:59 之间的时间内生成此输出

now:   15-Mar-2016 09:15:37.721AM
trunc: 15-Mar-2016 09:00:00.000AM
round: 15-Mar-2016 09:00:00.000AM

and, for a time between 09:30:00 and 09:59:59并且,在 09:30:00 和 09:59:59 之间的时间

now:   15-Mar-2016 09:45:50.925AM
trunc: 15-Mar-2016 09:00:00.000AM
round: 15-Mar-2016 10:00:00.000AM

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

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