Convert timestamp string to long in java
Asked Answered
N

6

10

I have to fetch time stamp from DB and retrieve only time and compare two time.

//below are the string values

 String st1 = "2015-07-24T09:39:14.000Z";      
 String st2 = "2015-07-24T09:45:44.000Z";

//retrieving only time 09:39:14

 String s = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));

//string to Long.

 Long time = Long.parseLong(s);

 Long tim1=Long.valueOf(s).longValue();

Error:

java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
Nozzle answered 30/7, 2015 at 4:43 Comment(3)
So essentially you want to do 'Long.toString("09:39:14")'. That won't work cause it's not a number. What long value are you expecting? Is it the number of milliseconds since January 1, 1970, 00:00:00 GMT?Nickola
HI @user2341963 , I am expecting this :09:39:14 . so that i can compare both the timeNozzle
@thanga By the way, if you are fetching the date-time values from a database you should be receiving date-time objects, probably java.sql.Timestamp, rather than Strings.Faunus
G
3

Another option is by using SimpleDateFormat (May not be the best compare to JODA Time)

public static void main(String[] args) throws ParseException {
        String st1 = "2015-07-24T09:39:14.000Z";
        String st2 = "2015-07-24T09:45:44.000Z";

        String time1 = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));
        String time2 = st2.substring(st2.indexOf("T") + 1, st2.indexOf(".0"));

        Date dateTime1 = new java.text.SimpleDateFormat("HH:mm").parse(time1);
        Date dateTime2 = new java.text.SimpleDateFormat("HH:mm").parse(time2);

        System.out.println(dateTime1.after(dateTime2));

    }
Gladine answered 30/7, 2015 at 4:57 Comment(0)
A
17

Try this way, Example code:

java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2015-07-24T09:45:44.000Z");
long tsTime2 = ts2.getTime();
Agrimony answered 30/7, 2015 at 4:49 Comment(2)
Are you sure about this? The doc says the string must be in JDBC format (SQL format). That means a SPACE between the date portion and time-of-day portion. The T in the middle is ISO 8601 format.Faunus
@BasilBourque Yeah, the "T" causes an IllegalArgumentException. And then the "Z" causes a NumberFormatException.Janeljanela
T
3

The simplest solution would be to use Java 8's Date/Time API

LocalDateTime from = LocalDateTime.parse("2015-07-24T09:39:14.000Z", DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime to = LocalDateTime.parse("2015-07-24T09:45:44.000Z", DateTimeFormatter.ISO_DATE_TIME);
System.out.println(from + " - " + to);

LocalTime fromTime = from.toLocalTime();
LocalTime toTime = to.toLocalTime();

System.out.println(fromTime + " - " + toTime);

System.out.println(fromTime + " before " + toTime + " = " + fromTime.isBefore(toTime));
System.out.println(fromTime + " after " + toTime + " = " + fromTime.isAfter(toTime));
System.out.println(fromTime + " equals " + toTime + " = " + fromTime.equals(toTime));
System.out.println(fromTime + " compareTo " + toTime + " = " + fromTime.compareTo(toTime));

Which outputs

2015-07-24T09:39:14 - 2015-07-24T09:45:44
09:39:14 - 09:45:44
09:39:14 before 09:45:44 = true
09:39:14 after 09:45:44 = false
09:39:14 equals 09:45:44 = false
09:39:14 compareTo 09:45:44 = -1

If you're not using Java 8, then use Joda-Time which works in similar way

Joda-Time example...

import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.format.ISODateTimeFormat;

public class JodaTimeTest {

    public static void main(String[] args) {
        LocalDateTime from = LocalDateTime.parse("2015-07-24T09:39:14.000Z", ISODateTimeFormat.dateTime());
        LocalDateTime to = LocalDateTime.parse("2015-07-24T09:45:44.000Z", ISODateTimeFormat.dateTime());

        LocalTime fromTime = from.toLocalTime();
        LocalTime toTime = to.toLocalTime();

        System.out.println(fromTime + " - " + toTime);

        System.out.println(fromTime + " before " + toTime + " = " + fromTime.isBefore(toTime));
        System.out.println(fromTime + " after " + toTime + " = " + fromTime.isAfter(toTime));
        System.out.println(fromTime + " equals " + toTime + " = " + fromTime.equals(toTime));
        System.out.println(fromTime + " compareTo " + toTime + " = " + fromTime.compareTo(toTime));
    }

}

Which outputs

09:39:14.000 - 09:45:44.000
09:39:14.000 before 09:45:44.000 = true
09:39:14.000 after 09:45:44.000 = false
09:39:14.000 equals 09:45:44.000 = false
09:39:14.000 compareTo 09:45:44.000 = -1
Taking answered 30/7, 2015 at 4:49 Comment(5)
Hi @Taking , DateTimeFormatter.ISO_DATE_TIME); getting error here..imported joda-time. thanksNozzle
@thanga Joda-Time example addedTaking
@thanga Glad it could helpTaking
OP wanted to convert timestamps to longs, but none of your outputs show any longs.Janeljanela
@Janeljanela "retrieve only time and compare two time" - I skipped the title and went to the core issue - time comparison should NEVER be done by comparing long values, it should be done through appropriate librariesTaking
G
3

Another option is by using SimpleDateFormat (May not be the best compare to JODA Time)

public static void main(String[] args) throws ParseException {
        String st1 = "2015-07-24T09:39:14.000Z";
        String st2 = "2015-07-24T09:45:44.000Z";

        String time1 = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));
        String time2 = st2.substring(st2.indexOf("T") + 1, st2.indexOf(".0"));

        Date dateTime1 = new java.text.SimpleDateFormat("HH:mm").parse(time1);
        Date dateTime2 = new java.text.SimpleDateFormat("HH:mm").parse(time2);

        System.out.println(dateTime1.after(dateTime2));

    }
Gladine answered 30/7, 2015 at 4:57 Comment(0)
F
2

tl;dr

myResultSet.getObject(                         // Use JDBC 4.2 or later to get *java.time* objects rather than mere strings.
    … ,                                        // Specify the column in database of type `TIMESTAMP WITH TIME ZONE`.
    Instant.class                              // Extract from database as a `Instant` object in UTC, via JDBC.
)
.atZone( ZoneId.of( "Africa/Tunis" ) )         // Adjust into a time zone other than UTC. Returns a `ZonedDateTime` object.
.toLocalDate()                                 // Extract the date-only value, without time-of-day and without time zone. Returns a `LocalDate` object.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )   // Determine the first moment of the day (not always 00:00). Returns a `ZonedDateTime` object.

And…

Duration.between( zdtStartOfDay , zdt )        // Represent the span of time between the first moment of the day and the target moment. Each argument is a `ZonedDateTime` object here.
    .toMillis()                                // Get entire span as a count of milliseconds. Returns a `long` primitive.
  • No need for strings.
  • No need for java.sql.Timestamp.

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.sql.Timestamp & Date & Calendar.

The Answer by MadProgrammer is headed in the right direction by using java.time but uses the wrong class: LocalDateTime class purposely lacks any concept of time zone or offset-from-UTC but our input string does. The Z on the end of the input String is short for Zulu and means UTC. Throwing away valuable information (zone/offset info) is not a good practice.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.parse( "2015-07-24T09:39:14.000Z" ) ;

Smart objects, not dumb strings

I have to fetch time stamp from DB and retrieve only time and compare two time.

below are the string values

Use appropriate objects to exchange data with your database, not mere strings.

As of JDBC 4.2, you can directly exchange java.time objects via getObject & setObject.

Instant instant = myResultSet( … , Instant.class ) ;

You just fetched a date-time directly from a database column of type similar to the SQL-standard TIMESTAMP WITH TIME ZONE.

For sending data to the database, use a PreparedStatement with placeholders.

myPreparedStatement.setObject( … , instant ) ;

The Instant object retrieved via JDBC from the database is in UTC, by definition. To get the time-of-day, you must specify the wall-clock time of the region expected by the user (the time zone).

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;

Apply that time zone to get a ZonedDateTime object. The Instant and the ZonedDateTime represent the same moment, the same point on the timeline. This is a crucial concept to understand. Two friends talking on the phone, one in Québec Canada and one in Paris France will each look up to a clock on the wall simultaneously at the same moment yet see a different time in use by the people of their particular region.

ZoneDateTime zdt = instant.atZone( z ) ;

If you care only about the time-of-day, extract a LocalTime object.

LocalTime lt = zdt.toLocalTime(); 

Generate a String in standard ISO 8601 format.

String output = lt.toString();

Generate a string in localized format.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = lt.format( f ) ;

But you seem to want a count of something since the start of the day – your Question is not clear. Perhaps you want a count of whole seconds, or milliseconds, or I don't know what.

We must get the start of the day in the desired/expected time zone. Do not assume the day starts at the time 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. Let java.time determine the start of the day.

ZonedDateTime zdtStartOfDay = zdt.toLocalDate().atStartOfDay( z ) ;

Calculate the elapsed span of time as a Duration.

Duration d = Duration.between( zdtStartOfDay , zdt ) ;

Extract the entire span as a number of whole seconds.

long secondsSinceStartOfDay = d.toSeconds() ;

Extract the entire span as a number of milliseconds.

long millisSinceStartOfDay = d.toMillis() ;

Beware of data loss. The java.time classes have resolution of nanoseconds, so you are ignoring the finer parts of the value if present when you call the to… methods.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Faunus answered 8/3, 2018 at 22:42 Comment(0)
P
1
        String date = "2015-07-24T09:39:14.000Z";
        //Now we are getting the time only from the above string.
        String time = date.substring(12, 19); 
        System.out.println("Time is: "+time);
        //Since we cannot convert symbols like":" to long we are removing them.
        String timeInLong = time.replaceAll(":", "");
        System.out.println("Time in long format : "+Long.parseLong(timeInLong));
Pent answered 30/7, 2015 at 4:54 Comment(0)
L
0

you can try with the next code, I use the library joda-time

java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2015-07-24T09:45:44.000Z"); long dateLong=new DateTime(ts2).toDate().getTime();

Lyso answered 16/1, 2017 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.