get java Timezone id from +0000 format - java

I'm only getting this string "+0800" for a timezone from ihealth api. How can I get the corresponding java timezone id (like "US/Central") from this.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("Z");
try {
Date date = sdf.parse("+0800");
cal.setTime(date);
System.out.println(cal.getTimeZone().getID());
} catch (Exception e) {
System.out.println("error" + e.getMessage());
}
but this always prints "Etc/UTC" which is not "+0800". what am I missing here?

The difficulty in what you are asking is that there are (almost?) always many timezone names associated with a given offset. So, for an offset of "+0800" we can do
int rawOffset = 8 * 3600000; // +0800 hours converted to milliseconds
String[] tzIds = java.util.TimeZone.getAvailableIDs(rawOffset);
for (String id : tzIds) {
System.out.println(id);
}
and see the list
Antarctica/Casey
Asia/Brunei
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Harbin
Asia/Hong_Kong
Asia/Kashgar
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Macao
Asia/Macau
Asia/Makassar
Asia/Manila
Asia/Shanghai
Asia/Singapore
Asia/Taipei
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Australia/Perth
Australia/West
CTT
Etc/GMT-8
Hongkong
PRC
Singapore
If you want "the corresponding java timezone id" (emphasis mine) then I guess you'll have to pick one. ;)

Provided you use Java 8 you can use ZoneOffset
For example
ZoneOffset zoneOffset = ZoneOffset.of("+0200");
TimeZone timezone = TimeZone.getTimeZone(zoneOffset));
Edit: ZoneOffset.of() accepts offsetId, which is different from the 4 digits representation, so this would not solve the problem.

Try this:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("Z");
try {
Date date = sdf.parse("-0600");
cal.setTime(date);
System.out.println(sdf.format(date));
} catch (Exception e) {
System.out.println("error" + e.getMessage());
}

Related

SimpleDateFormat not formatting offset date time correctly

I got a timestamp as follows, 2019-10-17T07:10:39.021+10:30 but when I parse through the SimpleDateFormat then print again, it appear as 2019-10-17T07:40:39.021+11:00
Looks like it added the 30min to time then change the time zone. Is there is a way to fix that.
Date date = null;
String value = "2019-10-17T07:10:39.021+10:30";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.getDefault());
System.out.println("input :" + value);
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("output :" + sdf.format(date));
Result
input :2019-10-17T07:10:39.021+10:30
output :2019-10-17T07:40:39.021+11:00
Should be same as input.
The date string you have 2019-10-17T07:10:39.021+10:30consists of offset, so from java-8 you can use OffsetDateTime
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetDateTime dateTime = OffsetDateTime.parse(date);
System.out.println(dateTime.toString()); //2019-10-17T07:10:39.021+10:30
Why are you using Locale.getDefault(), that parameter is not necessary. Can you try just calling it as below,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

Convert UTC time to local time java Android

Im retrieving some values from a json service and the retrieved datetime values are stored in UTC format.
i've tried a lot of sample codes to convert the datetime values to user local timezone but im still getting the same value after conversion.
This is what i have actually: (copied from other posts)
String sJsonDate = "2015-07-08T12:08:13.0625+00:00";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date localDateTime = simpleDateFormat.parse(sJsonDate);
} catch (ParseException e) {
e.printStackTrace();
}
The result value (localDateTime) is the same as the original value.
I am in Paraguay (GMT-4) and the resulting values needs to be minus one hour diference, like this: ("2015-07-08 07:13:25") (The values are stored in Argentina)
Help please!
I've found the solution, we are using day light savings so i had to disccount one hour to the resulting datetime.
So, i share the code for someone else:
public Date getDateInTimeZone(Date currentDate, String timeZoneId) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
Date localDateTime = new Date(currentDate.getTime() + timeZone.getOffset(currentDate.getTime()));
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(localDateTime.getTime());
if (timeZone.useDaylightTime()) {
// time zone uses Daylight Saving
cal.add(Calendar.MILLISECOND, timeZone.getDSTSavings() * -1);// in milliseconds
}
return cal.getTime();
}
Usage:
String sDate = "2015-07-08T12:08:13.0625+00:00";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date theDate = simpleDateFormat.parse(sDate);
Date localDateTime = getDateInTimeZone(theDate, TimeZone.getDefault().getID());
} catch (ParseException e) {
e.printStackTrace();
}

While formatting GMT time to GMT+01:00 an extra hour is being added

I am facing the problem of an hour being added to the time after formating only in GMT+01:00.
Here is how i am doing it:
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
// Change Start date according to the Locale time
formattor.setTimeZone(TimeZone.getTimeZone("GMT"));
date1 = formattor.parse("2015-03-26 11:17:41");
formattor.setTimeZone(TimeZone.getDefault());
String start = formattor.format(date1);
// Change End date according to the Locale time
formattor.setTimeZone(TimeZone.getTimeZone("GMT"));
date1 = formattor.parse("2015-03-26 13:17:00");
formattor.setTimeZone(TimeZone.getDefault());
String end = formattor.format(date1);
System.out.println(start + " - " + end);
} catch (ParseException e) {
e.printStackTrace();
}
Output:
2015-03-26 12:17:41 - 2015-03-26 14:17:00
I am facing the same problem with Joda-Time.
I have tested it with GMT+01:00, West Africa Standard Time
That's very obvious since your getDefault () would make the Timezone to GMT+01:00 hence you're seeing the same. Reframe the question if this is not what you're expecting.

Wrong timezone in XMLGregorian calendar

I am using the below code to set a XMLGregorianCalendar field in webservice
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date dateOfBirth = null;
try {
dateOfBirth = format.parse(adult.getDob_day() + "-" + adult.getDob_month() + "-"
+ adult.getDob_year() + " 00:00:00");
} catch (Exception e) {
log.error("Error while parsing dateOfBirth. Cause " + e.getMessage());
e.printStackTrace();
}
passenger.setDateOfBirthField(convertToXMLCalendar(dateOfBirth));
The method convertToXMLCalendar is as below
private XMLGregorianCalendar convertToXMLCalendar(Date date) {
XMLGregorianCalendar xmlCalendar = null;
GregorianCalendar calendar = new GregorianCalendar();
if (date != null) {
try {
calendar.setTime(date);
xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
} catch (Exception e) {
log.error("Error while converting to XMLGregorianCalendar. Cause " + e.getMessage());
// e.printStackTrace();
}
}
return xmlCalendar;
}
My server location timezone is +03:00. But in few random scenarios the timezone is being send as +04:00 in SOAP request.
<ns7:dateOfBirthField>1955-08-27T00:00:00.000+04:00</ns7:dateOfBirthField>
Due to this the service is receiving the date as one day lesser than actual date. If I send 03-06-2014 00:00:00 its reaching the service as 02-06-2014 11:00:00.
If I set the time as 12:00:00 instead of 00:00:00 will it fix the issue. But whats the reason for this timezone change?
Your SimpleDateFormat doesn't specify a time zone, so it's using your local time zone. I would suggest:
Not parsing a value at all. You've got the individual day, month and year - so use that directly with a calendar!
Pass a Calendar to convertToXMLCalendar instead of a date... if you need to at all (see below)
Specify the time zone of the calendar as UTC if you really want to... although fundamentally I'd expect a dateOfBirth value to be just a date, to be honest, e.g. 1955-08-27. That way you're not specifying a time zone at all.
In fact, given that you've got the year/month/day, I'd just create an XMLGregorianCalendar directly from those values:
XMLGregorianCalendar calendar = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(adult.getDob_year(),
adult.getDob_month(),
adult.getDob_day(),
DatatypeConstants.FIELD_UNDEFINED); // No time zone
Then you're representing a date rather than a dateTime, which is what fits your data.
Your calendar does not specify the time zone. I believe, just by modifying the convertToXMLCalendar method, we can get rid of this problem
private static XMLGregorianCalendar convertToXMLCalendar(Date date) {
XMLGregorianCalendar xmlCalendar = null;
GregorianCalendar calendar = new GregorianCalendar();
// You can set GMT time zone or Default or whatever
//TimeZone myzone = TimeZone.getTimeZone("GMT");
TimeZone myzone = TimeZone.getDefault();
calendar.getInstance(myzone);
if (date != null) {
try {
calendar.setTime(date);
xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
} catch (Exception e) {
e.printStackTrace();
}
}
return xmlCalendar;
}

Java ParseException while attempting String to Date parsing

I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories