Wednesday, September 25, 2019

Evolution of 'java.util.Date' to 'java.time.Instant' considering date/time format specifier and timezones

Java API for datetime formatters have evolved as well
from
import java.util.Date
import java.util.Calendar;
and
import java.text.SimpleDateFormat;
import java.text.DateFormat;

to
import java.time.format.DateTimeFormatter;

Traditional code style


    public Timestamp convertStringToTimestamp(String str_date) {
       
        try {
            DateFormat formatter;
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            Date date = (Date) formatter.parse(str_date);

            java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());

            return timeStampDate;
        } catch (ParseException e) {
            logger.error("Exception happened here:" + e);
            return null;
        }
    }


OR

        // Must create new SimpleDateFormat and TimeZone on each method invocation since neither of these classes are thread-safe.
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return simpleDateFormat.format(new Timestamp(System.currentTimeMillis()));
       
Sample Output
2019-09-25T10:07:19.839Z
       

Database timestamp impendence was always there

import java.sql.Timestamp;


Newer style


private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
..
    public static String getCurrentTimestamp() {
        // No need to create new DateTimeFormatter or ZoneOffset on each method invocation since both of these classes are thread-safe.
        return TIMESTAMP_FORMATTER.format(OffsetDateTime.now().withOffsetSameInstant(ZoneOffset.UTC));
    }
..

Sample Output
2019-09-25T10:07:19.839Z

Plz Note: Observe the use of new formatter class (s)

import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;


   
   
Next Generation Compact Style


import java.time.Instant;
..
System.out.println(Instant.now());


   
Sample Output
2019-09-25T10:07:19.839Z    


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Followers