Monday 6 April 2020

How to set time zone for java.util.Date

Approach 1: Using setTimeZone method of SimpleDateFormat
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = simpleDateFormat.parse("2020-04-07T09:45:02");

Approach 2: Using ZonedDateTime
ZonedDateTime zonedDateTime = LocalDateTime.parse("2020-04-07T09:45:02").atZone(ZoneId.of("UTC"));
date = Date.from(zonedDateTime.toInstant());

Approach 3: Using 'TimeZone.setDefault'
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
date = new Date();

App.java
package com.sample.app;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;

public class App {

 public static void main(String args[]) throws ParseException {
  // Approach 1
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
  Date date = simpleDateFormat.parse("2020-04-07T09:45:02");

  System.out.println("date : " + date);

  //Approach 2
  ZonedDateTime zonedDateTime = LocalDateTime.parse("2020-04-07T09:45:02").atZone(ZoneId.of("UTC"));
  date = Date.from(zonedDateTime.toInstant());
  System.out.println("date : " + date);

  date = new Date();
  System.out.println("Date before setting timezone : " + date);

  //Approach3
  TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

  date = new Date();
  System.out.println("Date before setting timezone : " + date);
 }
}

Sample Output

date : Tue Apr 07 15:15:02 IST 2020
date : Tue Apr 07 15:15:02 IST 2020
Date before setting timezone : Tue Apr 07 10:10:16 IST 2020
Date before setting timezone : Tue Apr 07 04:40:16 UTC 2020


You may like
Previous                                                    Next                                                    Home

No comments:

Post a Comment