user3174886 user3174886 - 1 month ago 24
Groovy Question

Format current local time to 'MM/d/yyyy h:m:s:S a' format in groovy

I'm trying to format the current time in the format of "11/04/2016 09:48:03.5719 AM" using groovy. I'm getting error on my second line. Any suggestion to fix it?

Note: On my first line of code it is returning the date formatted as Fri Nov 04 9:48:03 EDT 2016.

def mydate = new Date(System.currentTimeMillis())
def date = Date.parse('EEE MMM d h:m:s z yyyy', mydate).format('MM/d/yyyy h:m:s.S a')
log.info mydate
log.info date

Rao Rao
Answer

You just need to use date with formatting pattern as shown below:

def dateTime = new Date().format('MM/d/yyyy h:m:s.S a')
log.info "Current date and time: ${dateTime}"