简体   繁体   中英

format date in groovy and save in desired format with milliseconds

I'm trying to get a full date with milliseconds.

I tried following

        Date callTime = new Date();

        String formattedDate = callTime.format('MM/dd/yyyy HH:mm:ss.SSS');

        println "formattedDate : " + formattedDate;

        def saveThisDate = new Date().parse("MM/dd/yyyy HH:mm:ss.SSS", formattedDate);

        println "saveThisDate : " + saveThisDate;

And it gave output as following

formattedDate : 12/22/2014 15:51:47.427
saveThisDate : Mon Dec 22 15:51:47 IST 2014

where the formattedDate gives correct output but I've to save it in a date so i tried doing saveThisDate . But it doesn't save milliseconds.

Where I'm doing wrong?

Dates are just dates, they don't have a format. You only give a data type a format when you convert it to a String. Create a String from the Date and give it the format you need.

It saves, You need to format it as well:

Date callTime = new Date();

String formattedDate = callTime.format('MM/dd/yyyy HH:mm:ss.SSS');

println "formattedDate : " + formattedDate;

def saveThisDate = new Date().parse("MM/dd/yyyy HH:mm:ss.SSS", formattedDate);

println "saveThisDate : " + saveThisDate.format('MM/dd/yyyy HH:mm:ss.SSS');

if you don't do additional formatting, the saveThisDate is printed out in default date format (depends on locale of your machine) and it doesn't include ms.

follow Opal's example

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