I have written following code. I want to get Date object in UTC format.
I am able to get expected date string in UTC using SimpleDateFormat
. But using same SimpleDateFormat
object, I am not able to get object in UTC format. It is returning object with IST format.
After searching, I found that Date object doesn't store timestamp info.
How can I get date object in UTC format ?
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class dddd { /** * @param args */ public static void main(String[] args) { System.out.println("Input - "+1393572325000L); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); Date date= new Date(1393572325000L); String dateString = formatter.format(date); System.out.println("Converted UTC TIME (using Format method) : "+dateString); Date date2 =null; try { date2 = formatter.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } System.out.println("Parsed Date Object (using Parse method) : "+date2); System.out.println("Expected Date Object : Fri Feb 28 07:25:25 UTC 2014"); } }
This prints following output :
Input - 1393572325000 Converted UTC TIME (using Format method) : 2014-02-28 07:25:25 Parsed Date Object (using Parse method) : Fri Feb 28 12:55:25 IST 2014 Expected Date Object : Fri Feb 28 07:25:25 UTC 2014
To convert a JavaScript date object to a UTC string, you can use the toUTCString() method of the Date object. The toUTCString() method converts a date to a string, using the universal time zone. Alternatively, you could also use the Date. UTC() method to create a new Date object directly in UTC time zone.
Date time with full zone information can be represented in the following formats. dd/MM/uuuu'T'HH:mm:ss:SSSXXXXX pattern. e.g. "03/08/2019T16:20:17:717+05:30" . MM/dd/yyyy'T'HH:mm:ss:SSS z pattern.
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); f. setTimeZone(TimeZone. getTimeZone("UTC")); System. out.
Java OffsetDateTime class is one of the important class to get current UTC time. OffsetDateTime is an immutable representation of a date-time with an offset that is mainly used for storing date-time fields into the precision of nanoseconds.
final Date currentTime = new Date(); final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println("UTC time: " + sdf.format(currentTime));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With