SP M
SP M

Reputation: 201

date to epoch conversion

Can anybody tell me how to convert date to epoch in java. e.g. 2011-05-01 13:12:20 IST or 2011-05-01 14:11:10 PST to epoch. I am able to convert using 2011-05-01 13:12:20 format but when I use timezone alongwith it I am not getting correct result.

Upvotes: 0

Views: 228

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338516

java.time

Using the java.time classes.

String input = "2011-05-01 13:12:20".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "Asia/Kolkata" ) );

If by “epoch”, you mean a count of whole seconds or milliseconds from the epoch reference date of first moment of 1970 in UTC (often referred to as Unix Time), then interrogate the ZonedDateTime object via an extracted Instant object.

long wholeSecondsSinceEpoch = zdt.toInstant().getEpochSecond();
long millisecondsSinceEpoch = zdt.toInstant().toEpochMilli();

Upvotes: 0

Dunes
Dunes

Reputation: 40693

Construct a SimpleDateFormat with a string pattern that matches the date format you have. The "Date and Time" section and the "Examples" section should give you more than enough help on how to construct your date format string

Then simply do the following to get your date (with the appropriate date format string).

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

Date date = sdf.parse("15/01/2012");

Upvotes: 1

Related Questions