Search code examples
javadatetimeutc

How to get UTC time without SimpleDateFormat?


I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.


Solution

  • So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.

    public class DateTimeHelper {
    
        public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
    
        private Date date = new Date();
        private final SimpleDateFormat format;
    
        public DateTimeHelper(String dateTimeFormat) {
            format = new SimpleDateFormat(dateTimeFormat, Locale.US);
        }
    
        public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
            this(dateTimeFormat);
    
            try {
                format.setTimeZone(timeZoneUTC);
                Date utc = format.parse(utcTimeString);
                format.setTimeZone(TimeZone.getDefault());
                String local = format.format(utc);
                date = format.parse(local);
            } catch (ParseException e) {
                // nothing
            }
        }
    
        public Date getDate() {
            return date;
        }
    
        public Date toUtc() {
    
            String temp = toString();
            format.setTimeZone(timeZoneUTC);
            try {
                return format.parse(temp);
            } catch (ParseException e) {
                return date;
            }
        }
    
        @Override
        public String toString() {
            format.setTimeZone(TimeZone.getDefault());
            return format.format(date);
        }
    
        public String toUtcString() {
            format.setTimeZone(timeZoneUTC);
            return format.format(date);
        }
    }
    

    And another one that's easier to use:

    public class MySqlDateTimeHelper extends DateTimeHelper {
    
        public MySqlDateTimeHelper() {
            super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
        }
    
        public MySqlDateTimeHelper(String utcTimeString) {
            super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
        }
    
        public static String getCurrentTimestampUtc() {
            MySqlDateTimeHelper current = new MySqlDateTimeHelper();
            return current.toUtcString();
        }
    }