简体   繁体   中英

Convert milliseconds to Date in specific format

Using below code , the output is 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?

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:

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

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

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

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