How to convert Date String to joda DateTime? - java

I have a date string "Wed Nov 20 00:00:00 IST 2019". How do I convert it to joda DateTime with the pattern "yyyyMMdd".
dateObject.setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"));

The problem with your String pattern is, that JodaTime does not recognize the 'IST' timezone. (See http://joda-time.sourceforge.net/timezones.html for a list of supported time zones.)
If you always want to parse the date in the same time zone, you could use:
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss 'IST' yyyy").withZone(DateTimeZone.forID("Indian/Mahe"));
DateTime parsed = DateTime.parse("Wed Nov 20 00:00:00 IST 2019", dateTimeFormatter);
Note that I have used IST as a string literal in the pattern format, i.e., this will only work if your date strings always includes the "IST" string.
To add fixed time zone information to your parsed date use withZone on the formatter. I picked a random Indian timezone known to JodaTime, "Indian/Mahe" in this case. Look up the one that matches your time zone in the list of supported time zones.

Related

Change GMT to EST time in Java 6

I am trying to convert a GMT time zone from other server to EST considering day light saving to display the correct date but not able to do.
The GMT time format is coming in json String as "yyyy-MM-dd 'T' HH:mm:ss 'Z'". To this format we are setting time zone as EST but not getting correct result.
Example - date coming as "2020-06-02T03:53:57Z" , while the correct date in EST when created was "2020-06-01T11:53:57Z".
To convert between two explicit time zones, specify those time zones on the SimpleDateFormat objects used to parse and re-format the date string.
String input = "2020-06-02T03:53:57Z";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = inputFormat.parse(input);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
outputFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(outputFormat.format(date));
Output
2020-06-01 23:53:57 EDT
As you can see, in June, the time zone is EDT, not EST, and it is certainly not Z, aka UTC.

Convert String to ZonedDateTime and change TimeZone

I have this string "Tue Apr 09 2019 12:59:51 GMT+0300"
I want to convert to ZonedDateTime.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss OOOO");
ZonedDateTime zdt = ZonedDateTime.parse(a, dtf);
After convert to ZonedDateTime, I want to change the timezone from GMT+0300 to other timezone.
My first problem is at parse. I get:
DateTimeParseException: Text 'Tue Apr 09 2019 12:59:51 GMT+0300' could not be parsed at index 25 (at GMT+0300, I think OOOO it's not right, but I don't know what else it is)
After that I don't know how to change the timezone.
OOOO expects the a colon before minute field, as the doc says:
Four letters outputs the full form, which is localized offset text,
such as 'GMT, with 2-digit hour and minute field, optional second
field if non-zero, and colon, for example 'GMT+08:00'.
You can insert a : before the last 00 programmatically, then parse it.
Since your string contains an offset and no time zone, what do you want a ZonedDateTime for? OffsetDateTime is more appropriate.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd yyyy HH:mm:ss 'GMT'xx", Locale.ROOT);
String a = "Tue Apr 09 2019 12:59:51 GMT+0300";
System.out.println(OffsetDateTime.parse(a, dtf));
2019-04-09T12:59:51+03:00
A time zone is a place on earth and encompasses historic and known future changes in UTC offset in that place. A time zone is conventionally given in the region/city format, for example Asia/Rangoon.
Edit
I use ZonedDateTime because I use time zone in my app.
I’m unsure exactly what you mean. Maybe you have decided in advance which time zone you are using? For example:
ZoneId zone = ZoneId.of("Europe/Zaporozhye");
OffsetDateTime odt = OffsetDateTime.parse(a, dtf);
ZonedDateTime zdt = odt.atZoneSameInstant(zone);
System.out.println(zdt);
2019-04-09T12:59:51+03:00[Europe/Zaporozhye]
If for some reason you want to regard GMT+0300 as a time zone even though it isn’t, the parsing I showed first works with ZonedDateTime too:
System.out.println(ZonedDateTime.parse(a, dtf));
2019-04-09T12:59:51+03:00

Convert Date String Mon Mar 30 13:51:35 UTC 2015 to Date Object

I am trying to convert a string such as
String dateString = "Mon Mar 30 13:51:35 UTC 2015";
in a Date Object.
I tried this:
DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Date Object:"+sdf.parse(dateString));
But the output of the date object is
Mon Mar 30 15:51:35 CEST 2015
as you can see:
1) it forwards the string's time ahead to two hours
2) it changes UTC --> CEST
I tried many solutions, but nothing worked. What is the correct way to do this?
EDIT: my objective here is to have a Date object from that original String. That Date Object should have the same parameters as the date string. In this case, the original hours of day (13) is turned to 15, but the desired is for it to stay at 13. I need this because in my program I will need to compare two different date objects.
EDIT: JAVA 8 SOLUTION
Searching the more recent Java 8, I found a better and more elegant solution. Here is the code
String pattern = "EEE MMM dd HH:mm:ss SSS zzz yyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.UK).withZone(ZoneId.of("UTC"));
final ZonedDateTime parsed = ZonedDateTime.parse(dateString, formatter);
Furthermore, to compare it with, for example, the current time:
ZonedDateTime now = ZonedDateTime.now();
int compared = parsed.compareTo(now);
System.out.println("NOW:"+now.toLocalDateTime()+" PARSED:"+parsed.toLocalDateTime()+" COMPARED:"+compared);
You are doing it correctly. The date is being parsed correctly. You are just printing the date into your local computer timezone. When you do toString() to a date, prints the date in your local machine timezone.
Mon Mar 30 15:51:35 CEST 2015 == Mon Mar 30 13:51:35 UTC 2015
CEST is UTC +2
A java.util.Date does not have a time zone, practically speaking. There is a time zone inside but it cannot be set nor gotten. One of many poor design decisions made in these old date-time classes.
The Date::toString method applies your JVM’s current default time zone when generating the output string. Done with good intentions, but not helpful as it creates the illusion your Date object is in that zone when in fact it is not.
java.time
You are using a troublesome old legacy class, now supplanted by the java.time framework built into Java 8 and later.
Convert from a Date to an Instant, a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myJavaUtilDate.toInstant();
Call toString. The java.time classes use standard ISO 8601 formats when parsing/generating strings.
String output = instant.toString();
To create strings, convert from Instant to OffsetDateTime using the constant ZoneOffset.UTC. Then work with the java.time.format classes to generate the string.
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , ZoneOffset.UTC );
Search Stack Overflow for more info and examples. These issues have addressed hundreds of times already.
Instead of UTC, use GMT when getting the timezone.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Source
You already have the Date object. If you want to print it in format you want, you can use DateFormat to format the Date object as well:
Date date = sdf.parse(dateString);
System.out.println("Date Object:"+sdf.format(date));
// Use the date object ...

Convert GMT to BST Java

I have a date format yyyy/mm/dd hh:mm:ss in GMT format. I want to convert the date from GMT format to BST time. What's the simplest way to do this?
With Java 8, the easiest way is probably to:
parse the date into a LocalDateTime
use it to create a ZonedDateTime using GMT time zone
change the time zone to BST
get the LocalDateTime of that new date
Sample example:
String date = "2015/03/09 10:32:00";
LocalDateTime gmt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
ZonedDateTime instant = ZonedDateTime.of(gmt, ZoneId.of("GMT"));
LocalDateTime bst = instant.withZoneSameInstant(ZoneId.of("Europe/London")).toLocalDateTime();
System.out.println(bst);
If you change the month to July, for example, you should see an offset of one hour as expected.
(I assumed that BST is British Summer Time - it could also be Bangladesh Standard Time: in general it is better to use the full name of the time zone to avoid ambiguities).

How can I use Java's SimpleDateFormat to parse a timezone given as "GMT+0100 (BST)"?

I have a date that's in the form of:
Wed Aug 17 2011 09:57:09 GMT+0100 (BST)
and have a filter that takes a time in a certain format. The problem seems to be the time zone on the end, none of the format strings I'm putting in the filter seem to work for this type of date format.
For example,
Wed Aug 17 2011 09:57:09 GMT+0100 (BST)
EEE MMM dd yyyy HH:mm:ss zZ?
The time zone part of this, keeps throwing an error.
Can anyone tell me what the correct format to parse the time zones on these dates is?
"z" needs a colon between hours and minutes. "Z" is only +/-HHMM (i.e. no "GMT" prefix).
One way to parse it is: EEE MMM dd yyyy HH:mm:ss 'GMT'Z. The "BST" bit is ignored, and it's based on assumption that there's always "GMT" before offset.
I would parse out and interpret the time zone information separately, then use that to construct the Date/Calendar object in the proper time zone.
The following code seems to work well enough with your example:
String source = "Wed Aug 17 2011 09:57:09 GMT+0100 (BST)";
String tzid = "GMT" + source.substring(28, 31)
+ ":" + source.substring(31, 33);
TimeZone tz = TimeZone.getTimeZone(tzid);
// if (tz == null) ?
SimpleDateFormat f = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
f.setTimeZone(tz);
Date date = f.parse(source);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println(date);
Prints "Wed Aug 17 08:57:09 UTC 2011".
A more sophisticated approach would be to use regex to extract individual parts ("+/-", "hh" and "mm") of the time zone offset.
Alternatively, you can attempt to discern the 3-letter time zone id (the string in between ( and )), and use the corresponding Java TimeZone if it exists.
In your particular example, though, "BST" resolves to Bangladesh Time which is GMT+0600 so you're better off with the numeric offset. "BST" here should probably be taken as British Summer Time (GMT+0100). This can be important because numeric offsets do not indicate the use of daylight savings time, which can be in effect depending on the date.
A more heuristic routine could take this into account and attempt to resolve the name first, but verify that the GMT offsets match, and fallback on the simple "GMT+hh:mm" timezones otherwise.
If you can not find a pattern matching your use case, try:
try{
new Date("Wed Aug 17 2011 09:57:09 GMT+0100 (BST)")
}catch(Exception e)
{
// Parse exception
}

Categories

Resources