Uzair Khan
Uzair Khan

Reputation: 2970

Convert date string to timestamp, groovy

I have a date string as follows:

201805041235040000000

Which I would like to convert to timestamp with zone in Groovy. Tried this:

def timestamp = Date.parse("yyyyMMddHHmmss", timstamp).format("yyyy-MM-dd'T'HH:mm:ssZ");

But failed, got error:

No signature of method: static java.util.Date.parse() is applicable for argument types.

Let me know where am I going wrong.

Upvotes: 0

Views: 23993

Answers (4)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

This works...

String input = '201805041235040000000'

String timestamp = Date.parse('yyyyMMddHHmmss', input).format("yyyy-MM-dd'T'HH:mm:ssZ")

Upvotes: 2

Jyoti Jadhav
Jyoti Jadhav

Reputation: 307

Try this:

    String t2,st = "16/08/2007 09:04:34"
    SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss")
    Date date = sdf.parse(st)
    Timestamp timestamp = new Timestamp(date.getTime())
    t2 = timestamp.toString()

Hope it helps....

Upvotes: 3

Matias Bjarland
Matias Bjarland

Reputation: 4482

It is a bit unclear what you are looking for. If you just need a time stamp from parsing your date string, you can use the groovy extension Date.toTimestamp():

def ts = Date.parse("yyyyMMddHHmmssSSS", "201805041235040000000".take(17)).toTimestamp()

where the take(17) is there to discard any trailing zeros not included in the date pattern yyyyMMddHHmmssSSS. I made the assumption that three of the tailing zeros were milliseconds. If that's not the case:

def ts = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).toTimestamp()

what is unclear is what you mean when you say "with zone". So assuming you just want to include the current time zone information and generate a String, I don't see a reason why you should convert from date to timestamp in the first place (Timestamp after all is a Date as it inherits from Date). If you just need the timezone spelled out you can do:

def withZone = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).format("yyyy-MM-dd'T'HH:mm:ssZ")
println withZone

which on my machine where I'm sitting in Sweden prints out:

~> groovy withTimeZone.groovy 
2018-05-04T12:35:04+0200

Upvotes: 2

Evgeny Smirnov
Evgeny Smirnov

Reputation: 3026

timestamp must be string. Try this:

Date.parse("yyyyMMddHHmmss", timstamp?.toString()[0..13])
    .format("yyyy-MM-dd'T'HH:mm:ssZ")

Upvotes: 0

Related Questions