How to print UTC or GMT using SimpleDateFormat? [duplicate] - java

This question already has answers here:
Convert Java Date to UTC String
(7 answers)
How do you format current system datetime as UTC using String.format in Java?
(2 answers)
How to get UTC+0 date in Java 8?
(5 answers)
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I am trying to print a date in this format:
2023-01-11 09:25:52 UTC
But when I use date format:
yyyy-MM-dd HH:mm:ss Z
I get:
2023-01-11 09:29:25 +0100
While searching by existing question in stack overflow, I found similar questions but not with this exact format with "UTC" at the end. I found one that provided a solution to add the format as yyyy-MM-dd HH:mm:ss 'UTC' but then it would force the a GMT value to wrongly show UTC at the end.
Most of the answers explain how to get UTC value, but not how to print in this format
2023-01-11 09:25:52 UTC
Some solutions were also suggesting to use something else than SimpleDateFormat.
This question was marked as duplicated, but none of the post that were supposed to be duplicated had the info that I wanted.

Use a lowercase z instead of Z to get the offset instead of the id. And you have to set the time zone using simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")).
Example:
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(simpleDateFormat.format(date)); // 2023-01-11 08:41:17 UTC

If you create an instance of simpleDateFormat with yyyy-MM-dd HH:mm:ss Z date format is incorrect change to capital Z to small z,
then it works as expected.
2023-01-11 09:25:52 UTC

Related

Exact string to date and keep original format [duplicate]

This question already has answers here:
How to properly format the date?
(5 answers)
Get Date type object in format in java
(6 answers)
display Java.util.Date in a specific format
(11 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have looked around for help on this, but again, it's just one of those things that I cannot find a suitable answer to my specific issue.
Here's 2 very detailed (and helpful) SO posts that I've looked at:
Change date format in a Java string
Java string to date conversion
This is what I have:
//Date Formatter
SimpleDateFormat dateFormatter1 = new SimpleDateFormat("yyyy-MM-dd", new Locale("EN"));
SimpleDateFormat dateFormatter2 = new SimpleDateFormat("dd MMMM yyyy", new Locale("EN"));
//Convert to Date
Date dateToParse = dateFormatter1.parse("2024-01-01");
//Format OUTPUT date
String dateAsString = dateFormatter1.format(dateToParse);
System.out.println(dateAsString); //01 January 2024
//Convert OUTPUT date from STRING to DATE
Date dateToReturn = dateFormatter1.parse(dateAsString);
System.out.println(dateToReturn.toString()); //Mon Jan 01 00:00:00 SAST 2024
Note:
I used both DateFormatter and SimpleDateFormatter but got the same output.
The outputs are very different and what I am trying to achieve is to have my String created as a Date object in the exact same format.
I feel I am missing something but I just cannot figure out what.
The code I provided is a snippet from a bigger function that returns type Date
The function wasn't created by myself, I'm picking up from where someone else left off
Whenever you call a .toString() method on a Date, then the DateFormatter is not taken into account. The format of date you get is just a matter of default toString implementation of Date class.
To use formatter while printing, try something like this (instead of the last line in your snippet):
System.out.println(dateFormatter1.format(dateToReturn));
Date.toString() returns always returns a string in the format dow mon dd hh:mm:ss zzz yyyy.
You'll need to reuse the formatter's format method to get the initial string you expect

How to Parse Date in Java in Given Format? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 5 years ago.
I try to use java.util.Date date = Date.from( Instant.parse(minDates)); to parse the date string given in format Wed Jan 17 2001 00:00:00 GMT 0530.
I am not able to figure out, how to do that in JAVA.
The want to convert the given date string in given format
2013-05-22T00:00:00
May be i am not able to figure it out, properly. If someone have way to do that suggest me in Java Only.
Here is the solution:
String dateToParse = "Wed Jan 17 2001 00:00:00 GMT 0530";
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd YYYY HH:mm:ss");
SimpleDateFormat out = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss");
Date date = in.parse( dateToParse );
System.out.println( out.format( date ) );
It will work if all dates are in the same timezone (GMT 0530)
Else it should be modified to support it, but I suppose you have the same timezone.
You can do that by using SimpleDateFormat 'parse' API.
You can initialize your SimpleDateFormat with any valid time format such as yyyy-MM-dd HH:mm:ss z and then parse any string which adheres to this format.
reff. to http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
One addition tip, use JodaTime as the Date and SDF in Java are getting deprecated: http://www.joda.org/joda-time/
If you are using Java 8+, You can use java.time.OffsetDateTime (or Instant...) instead of java.util.Date, which is incredibly easy.
OffsetDateTime odt = OffsetDateTime .parse("2013-05-22T00:00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
Note that the second argument is optional in this case but you could have to specify one (with timezone id for example).
There is a solution without external which works with older version of Java and that manages timezones well. It consists of using JAXB's DataTypeConverter.
Date date = javax.xml.bind.DatatypeConverter.parseDateTime("2013-05-22T00:00:00+01:00").getTime();
Note that DatatypeConverter.parseDateTime returns a Calendar. You just need to call its getTime() method to convert is to a Date.

Android timestamp to local user time or date [duplicate]

This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 5 years ago.
How can I convert minutes from Unix timestamp to date and time in java? For example, timestamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.
I want to convert 1372339860 to 2013-06-27 13:31:00 GMT.
Edit: Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)
Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

How can I correctly parse this specific Date? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 7 years ago.
I could not find a correctly and clean working solution for my Date which is formatted like this:
2014-06-09T00:01+0200
(9th of June here)
Last I tried was this:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX", Locale.ENGLISH);
This just gives me an unparsable date exception. What do you think I should change?
replace XXX with Z,
String dateTimestr = "2014-06-09T00:01+0200";
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
s.parse(dateTimestr);
to print,
System.out.println(s.format(s.parse(dateTimestr)));
using Java 8,
OffsetDateTime dateTime = OffsetDateTime.parse("2014-06-09T00:01+02:00");
System.out.println(dateTime.toString());
Note that OffsetDateTime.parse would only work if your string is proper ISO8601 date format. If your date is in different format then you have to provide your OffsetDateTime.parse() with a proper formatter using DateTimeFormatter. i.e
OffsetDateTime.parse(yourStringDate, DateTimeFormatter formatter)
Use Z instead of XXX or one X
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.ENGLISH);
From the documentation:
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
The problem is XXX requires timezone format with a colon, i.e., 2014-06-09T00:01+02:00
Using Z instead of XXX or using XX (2 X's) should accept format without colon
Be careful with using one X as some have posted because this will disregard the last two digits of the timezone (e.g., 2014-06-09T00:01+02). This could be problematic if working with time zones in some countries like India where the time zone offset is +05:30. Note the following code..
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX").format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mmX").parse("2014-06-09T00:01+05:30")));
Will print 2014-06-08T14:01-05:00. The :30 in the timezone was lost when using one X. Documentation

How to convert UTC to PST in java [duplicate]

This question already has answers here:
Convert GMT to IST in java?
(5 answers)
Closed 6 years ago.
I am trying to convert time zone from UTC to GMT in java. I have tried several times and even used your guided method too. I am getting my output with correct timing in GMT format but along with "PDT 2012" written with it. Why so..?? I have tried hundreds of methods but can't get rid of it.
Please help me.
Thanks
For all Date / or DateTime related operations in Java I would recommend to use JodaTime Library
It is very useful to use Date/time with different point of views (calendar, timezone) and for computation as well: adding/substracting months, years, days and so on...
Since Java 8, an equivalent (improvement) of JodaTime is included in the JDK under the new package java.time (JSR-310) and no more needed to add it as dependency.
The author of JodaTime explains in his blog the difference between JodaTime and JSR-310.
Perhaps the following will be a starting point. It converts your current date to GMT:
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
TimeZone currentTimeZone = cal.getTimeZone();
int offset = currentTimeZone.getOffset(cal.getTimeInMillis());
Date adjustedTime = new Date(cal.getTimeInMillis() - offset);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormat.format(adjustedTime));
A couple of notes:
You are probably not able see the PST change to UTC because you don't set the timezone on the date format
You shouldn't really use the abbreviations like "GMT" anymore. It is better to use the full name in the id field.
You'll have to be a bit more creative if you happen to run the above code on a system that has its default time already set to GMT.

Categories