[ACCEPTED]-Convert UTC date into milliseconds-milliseconds

Accepted answer
Score: 14

EDIT: I'd missed the "ignoring the 30 time of day" part. It's now present, but 29 near the end...

The simplest approach is 28 probably to use SimpleDateFormat, having set the time zone 27 appropriately:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));

Date date = format.parse(text);
long millis = date.getTime();

(Setting the time zone is 26 the important bit here, as otherwise it 25 will interpret the value to be in the local time 24 zone.)

Alternatively, if you're doing anything 23 less trivial than this, use Joda Time which is a 22 much better date/time API. In particular, SimpleDateFormat isn't thread-safe 21 whereas DateTimeFormatter is:

// This can be reused freely across threads after construction.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
    .withLocale(Locale.US)
    .withZoneUTC();

// Option 1
DateTime datetime = formatter.parseDateTime(text);
long millis = dateTime.getMillis();

// Option 2, more direct, but harder to diagnose errors
long millis = formatter.parseMillis(text);

Now so far, we've parsed the 20 whole whole caboodle. The easiest way of 19 ignoring the date part is just to round 18 it off - after all, Java doesn't observe 17 leap seconds, so we can just truncate it:

long millisPerDay = 24L * 60L * 60L * 1000L; // Or use TimeUnit
long dayMillis = (millis / millisPerDay) * millisPerDay;

That 16 will "round towards 1970" so if 15 you have a date before 1970 it will round to the 14 end of the day - but I suspect that's unlikely 13 to be a problem.

With the Joda Time version 12 you could just use this instead:

DateTime dateTime = formatter.parseDateTime(text);
long millis = dateTime.toLocalDate().getLocalMillis();

I would 11 personally not go with the idea of just taking 10 a substring. Even though you're not actually 9 interested in preserving the hour/minute/second, I 8 think it's appropriate to parse what you've 7 been given and then throw away information. Aside 6 from anything else, it makes your code fail 5 appropriately with bad data, e.g.

"2012-06-100"

or

"2012-06-14 25:01:25"

indicate 4 problems in whatever's supplying you data, and 3 it's good to spot that rather than to continue 2 blindly just because the first 10 characters 1 are okay.

Score: 2

UPDATE: See the modern solution using java.time classes 35 in the correct Answer by Ole V.V..

Simpler

The answer by Jon Skeet is correct. And he 34 makes a good point about including, rather 33 than truncating, the time-of-day info while 32 parsing.

However, his code could be simplified. Especially 31 so because Joda-Time gained an important new method 30 in the latest versions: withTimeAtStartOfDay. This method supplants 29 all the "midnight"-related classes 28 and methods which are now deprecated.

Specifying 27 a Locale is a good habit, as shown in his code. But 26 in this particular case a Locale is not 25 necessary.

His answer correctly suggests 24 the Joda-Time library, far superior to using 23 java.util.Date, .Calendar, and java.text.SimpleTextFormat. Those 22 classes are notoriously troublesome, and 21 should be avoided. Instead use either Joda-Time 20 or the new java.time package built into Java 8 (inspired 19 by Joda-Time, defined by JSR 310).

First Moment Of The Day

You cannot 18 ignore time-of-day if what you want is a 17 count of milliseconds-since-epoch. I suspect 16 what you want is to change the time to first 15 moment of the day. In UTC, this always means 14 the time 00:00:00.000. But note that in local time zones, the 13 first moment may be a different time because 12 of Daylight Saving Time and possibly other anomalies.

ISO 8601

Your string 11 is nearly in standard ISO 8601 format, but we need 10 to swap a T for the SPACE in the middle. Then 9 we can feed the resulting string directly 8 to Joda-Time as Joda-Time has built-in formatters used 7 by default for standard strings.

Example Code

The following 6 example code assumes the intent of your 5 question is to parse a string as a date-time 4 value in UTC time zone, adjust the time to 3 the first moment of the day, and then convert 2 to number of milliseconds since Unix epoch (beginning 1 of 1970 in UTC).

String inputRaw = "2012-06-14 05:01:25";
String input = inputRaw.replace( " ", "T" );  // Replace SPACE with a 'T'.
DateTime dateTime = new DateTime( input, DateTimeZone.UTC );  // Parse, assuming UTC.
DateTime dateTimeTopOfTheDay = dateTime.withTimeAtStartOfDay();  // Adjust to first moment of the day.
long millisecondsSinceUnixEpoch = dateTimeTopOfTheDay.getMillis();  // Convert to millis. Use a 'long', not an 'int'.
Score: 1

java.time and JDBC 4.2

I am providing the modern answer. These 25 days (and for the last several years) you 24 should use java.time, the modern Java date 23 and time API, for your date and time work. And 22 since JDBC 4.2 you can directly retrieve 21 java.time objects from your database (and 20 also store them into it). A modern JPA implementation 19 (Hibernate at least since Hibernate 5) will 18 be happy to do the same. So forget about 17 SimpleDateFormat, Date and other old classes used in most of 16 the old answers. The mentioned ones are 15 poorly designed, and java.time is so much 14 nicer to work with.

Retrieve proper date-time objects from your database

I also recommend that 13 you don’t retrieve your UTC time as a string 12 from the database. If the datatype in SQL 11 is timestamp with time zone (recommended for UTC times), retrieve 10 an OffsetDateTime. For example:

    PreparedStatement pStmt = yourDatabaseConnection
            .prepareStatement("select utc_time from your_table where id = 7;");
    ResultSet rs = pStmt.executeQuery();
    if (rs.next()) {
        OffsetDateTime utcDateTime = rs.getObject("utc_time", OffsetDateTime.class);
        long millisecondsSinceEpoch = utcDateTime.truncatedTo(ChronoUnit.DAYS)
                .toInstant()
                .toEpochMilli();
        System.out.println("Milliseconds since the epoch: " + millisecondsSinceEpoch);
    }

If the type in SQL is dateTime or 9 timestamp without time zone, we probably need to 8 retrieve a LocalDateTime instead (details depending on 7 your JDBC driver and the time zone of your 6 database session). It goes in the same manner. For 5 converting your LocalDateTime to OffsetDateTime, see the conversion 4 below.

If you need to convert from a string

If you cannot avoid getting your UTC 3 time as a string as in the question, parse 2 it into a LocalDateTime and convert from there. For example:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String utcTimeString = "2012-06-14 05:01:25";
    long millisecondsSinceEpoch = LocalDateTime.parse(utcTimeString, formatter)
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println("Milliseconds since the epoch: " + millisecondsSinceEpoch);

Output:

Milliseconds 1 since the epoch: 1339650085000

Link

Score: 0

Use the Date object in combination with 4 SimpleDateFormat.

There is a method named 3 getTime() in Date which will return the 2 milliseconds for you.

Example that solves 1 your problem :

Date truc = new SimpleDateFormat( "y-m-d").parse( "2010-06-14");
System.out.println(truc.getTime());
Score: 0
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); //or whatever format you have
Date t = ft.parse('2014-03-20');

String result = String.format("%tQ", t);

System.out.printf("%tQ", t);

There are two methods here:

  1. you put the result milliseconds into a variable result
  2. printing it straight off.

0

More Related questions