Categories
date java

change timezone of date in java

In this post, we will learn to change timezone of date in java

In java by default new Date() will give you the system/server timezone.

Syntax
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeTimeZon {

	public static void main(String[] args) {
		try {
			Date date = new Date();
			System.out.println("Current Date Time : " + date);
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
			// In below line we are mentioned to convert into UTC
			dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
			String utcFormat = dateFormat.format(date);
			System.out.println("After converting into UTC format: " + utcFormat);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Current Date Time : Thu Jun 18 15:29:35 IST 2020
After converting into UTC format: 2020-06-18 09:59:35 UTC
Conclusion

In the above post, we learned to change timezone of date in java

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/date/ChangeTimeZon.java

Related Articles

calculate number days between two dates using java

Leave a Reply

Your email address will not be published. Required fields are marked *