Patrick Lorio
Patrick Lorio

Reputation: 5668

java time (Wed Feb 29 20:56:47 +0000 2012) to epoch

I have a database filled with timestamps in the following format:

Wed Feb 29 20:56:47 +0000 2012
Wed Feb 29 00:32:48 +0000 2012
Fri Apr 01 00:10:30 +0000 2011

I need to turn the into Epoch times to easily do calculations.

I want them to be seconds since 1970 (like what System.currentTimeMillis()/1000 does)

Does java have some method for this or do I have to parse and calculate it? Thanks in advance.

Upvotes: 1

Views: 211

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79095

Solution using java.time, the modern API:

Your date-time string has timezone offset value and therefore, it's a candidate to be parsed into OffsetDateTime object which you can convert to Instant. The function, Instant#toEpochMilli converts an instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d H:m:s X u", Locale.ENGLISH);
        OffsetDateTime odt = OffsetDateTime.parse("Wed Feb 29 20:56:47 +0000 2012", dtf);
        Instant instant = odt.toInstant();
        long epochSecond = TimeUnit.SECONDS.convert(instant.toEpochMilli(), TimeUnit.MILLISECONDS);
        System.out.println(epochSecond);
    }
}

Output:

1330549007

Try to avoid performing calculations yourself if you have standard API available (e.g. TimeUnit#convert used in the code above) to achieve what you would do with the calculation.

Learn more about java.time, the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500893

Well you have to parse it, but that's easy enough to do with SimpleDateFormat:

SimpleDateFormat format = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy",
                                               Locale.US);

Date date = format.parse(text);
long secondsSinceEpoch = date.getTime() / 1000;

On the other hand, it would be better if you stored the values in your database in a more appropriate column type to start with. Are you really storing them as text? If so, why?

Upvotes: 3

Related Questions