How to convert UTC to PST in java [duplicate] - java

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.

Related

Anomaly in hardcoding date in Java

There is an anomaly I have observed while setting dates in Java.
I am trying the following:-
Date date1 = new Date("10/12/2018");
So when I am printing the date, it is coming of future
It was printing this date:- 14 June 2019.
When I am doing the following:-
Date date1 = new SimpleDateFormat("dd/MM/yyyy").parse("10/12/2018");
It is showing the exact date. Can anyone please explain why this happened?
Thanks in advance.
java.time
To hardcode a date use the following:
LocalDate date2 = LocalDate.of(2018, Month.OCTOBER, 12);
System.out.println("Harcoded date: " + date2);
You will never get in doubt which is month, day and year. Output is:
Harcoded date: 2018-10-12
You should avoid the poorly designed and long outdated Date class and even more its deprecated constructors. Instead I am using LocalDate from java.time, the modern Java date and time API. Also a LocalDate represents a calendar date (without time of day), contrary to Date, which despite its name represents a point in time.
BTW I could not reproduce your problem. I get Fri Oct 12 00:00:00 CEST 2018 (which also agrees with the documentation, though this part of the documentation is very hard to read and understand).
Link: Oracle tutorial: Date Time explaining how to use java.time.
The Date() constructor (Note: it's deprecated !) doesn't know what is month and year.
USA: MM/dd/yyyy while Europe it's dd/MM/yyyy.
In the second form you are explicit. In the the first form it picks the wrong one.

java: ParseException: Unparseable date [duplicate]

This question already has answers here:
ParseException when parsing 3 character abbreviated month using SimpleDateFormat
(5 answers)
Closed 4 years ago.
i have a SimpleDateFormat format = new SimpleDateFormat("d M y H:m"); and i try to parse the String "8 Jan 2019 16:47" with it, but i get a ParseException. Did i create it the wrong way?
According to docs.oracle.com the M should recognize 3-letter-months.
Can anyone help me?
The official documentation: (https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)
You probably missed out this little note here:
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
Based on your example input, the following works:
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy HH:mm");
java.time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMM y H:mm", Locale.ENGLISH);
String stringToParse = "8 Jan 2019 16:47";
LocalDateTime dateTime = LocalDateTime.parse(stringToParse, formatter);
System.out.println(dateTime);
The output from this snippet is:
2019-01-08T16:47
What went wrong in your code?
SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome. I recommend you don’t use them in 2019.
As others have said you need three M for month abbreviation (no matter if you are using the outdated SimpleDateFormat or the modern DateTimeFormatter). One M will match a month number in 1 or 2 digits, for example 1 for January.
You should also specify a locale for your formatter. I took Jan to be English so specified Locale.ENGLISH. If you don’t specify locale, the JVM’s default locale will be used, which may work well on some JVMs and suddenly break some day when the default locale has been changed or you are trying to run your program on a different computer.
Link
Oracle tutorial: Date Time explaining how to use java.time.

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.

yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z' convert to date format

I receive the date from API in this format:
yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'
and convert it within this way:
String rawDate = "2017-05-11T15:46:48.2226756Z";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'", Locale.getDefault());
Date date = simpleDateFormat.parse(rawDate);
System.out.println(date); //Thu May 11 16:23:54 PDT 2017
However the date output is like that:
Thu May 11 16:23:54 PDT 2017
Output supposed to be:
Thu May 11 15:46:48 PDT 2017
How to convert the raw date properly?
SimpleDateFormat cannot handle any other number of decimals on the seconds than three (milliseconds), so there is no way to have it parse your string correctly. Furhermore the newer Java date and time classes are generally much more programmer-friendly and convenient. And they come with nanosecond precision (9 decimals on the seconds). So I am suggesting that you consider moving on to them.
As already commented Z means Zulu time zone, also known as UTC. So 2017-05-11T15:46:48.2226756Z means 15:46:48 UTC, equal to 8:46:48 Pacific Daylight Time. Your format is the ISO 8601 format for an instant, which the Instant class understand as its default, so parsing is easy:
Instant instant = Instant.parse(rawDate);
The result is
2017-05-11T15:46:48.222675600Z
Only thing to note about this is the two added zeroes. The toString method prints decimals in groups of three, enough groups to render the full precision. So with 7 decimals it prints 9.
To get the date in the Pacific time zone:
ZonedDateTime dateTime = instant.atZone(ZoneId.of("America/Los_Angeles"));
The result is what I predicted:
2017-05-11T08:46:48.222675600-07:00[America/Los_Angeles]
Now assume you got your raw date-time string from someone who misunderstood and really meant Thu May 11 15:46:48 PDT 2017 (it wouldn’t be the first time in history). Then you need to convert it to that. Again, while this would be cumbersome with the oldfashioned classes, it goes smoothly with the newer ones:
ZonedDateTime dateTime = instant.atOffset(ZoneOffset.UTC)
.atZoneSimilarLocal(ZoneId.of("America/Los_Angeles"));
The result is the one you asked for (except I am giving you all the decimals too):
2017-05-11T15:46:48.222675600-07:00[America/Los_Angeles]
For Android you get the newer date and time classes from the ThreeTenABP library.
Links
Oracle Tutorial: Trail: Date Time
The date and time classes for Android: ThreeTenABP
Question How to use ThreeTenABP in Android Project
The problem is that 'S' stands for milliseconds. So, in your case, you are telling it that the time is 15 hours, 46 minutes, 48 seconds and 2226756 milliseconds. If you add 2226756 milliseconds, i.e. 2226 seconds and 756 milliseconds to 15:46:48, you indeed get 16:23:54.
The easiest solution is probably to just find the period in your string, and truncate the string three places, later, i.e. convert it to:
2017-05-11T15:46:48.222
You can achieve this with the following line:
rawDate = rawDate.substring(0, rawDate.indexOf('.') + 4);
And then parse it with
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault());
Note that this does not correctly round the microseconds. In your case, for example, 222.6756ms should be rounded up to 223ms, not down to 222ms. If this matters, you can do this manually by examining the first dropped digit to see if it's 5 or above and adding a millisecond to date.
Update (re: Basil Bourque):
If you would like to actually respect the time-zone identifier in your time-string (which indicates UTC as explained below by Ole V.V.), you can simply add 'UTC' to the end of the string and parse it with that timezone in older versions of Java without using any additional libraries:
rawDate = rawDate.substring(0, rawDate.indexOf('.') + 4) + "UTC";
SimpleDateFormat sDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz",
Locale.getDefault());
Date date = sDF.parse(rawDate);
You can just use below to parse.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());

How to get the currently time only [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 7 years ago.
Wha would be the equivalent in Java for this C# code:
DateTime.Now.TimeOfDay //This
DateTime.Now.ToString("h:mm:ss tt") //Or This
I'm finding a lot of things, some of them may be deprecated because it has 2 years or more, others are really complex for such a simple thing, and I'm sure there is a simpler way to do so.
I tried:
import java.util.Date;
Date d = new Date();
System.out.println(d); //Result: Wed Oct 28 00:46:29 2015
If I try:
System.out.println(d.getTime()); //Result: 1446000426285
I need to get only time: H:mm:ss
You can use SimpleDateFormat in java. date.getTime() gives you the milliseconds since January 1, 1970, 00:00:00 GMT.
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
System.out.println(dateFormat.format(date));
Generally speaking, in Java, date/time objects are just a container for the amount of time which has passed since a given point in time (like the Unix epoch), so they tend not to have there own concept of formatting.
Formatting is normally managed by a supporting API, like java.text.DateFormat or java.time.format.DateTimeFormatter
If you're using Java 8, you could start with LocalTime
LocalTime time = LocalTime.now();
System.out.println(DateTimeFormatter.ISO_LOCAL_TIME.format(time));
which prints 13:51:13.466.
If you need a specific format, you can supply your own pattern to DateTimeFormatter, something like System.out.println(DateTimeFormatter.ofPattern("h:mm:ss a").format(time)); which prints 1:52:31 PM
Have a look at Date and Time Classes for more details

Categories