Dateformat adds extra 30 minutes to time - java

I'm using this Android code for converting milliseconds to mm:ss.SS format but in result dateformat adds 30 extra minutes in date.
Date date = new Date(millis);
DateFormat dateFormat= new SimpleDateFormat("mm:ss.SS", Locale.US);
best.add(dateFormat.format(date));\
Actually I want to convert milliseconds to m:ss.SS format. Is there any other best way to achieve this?
Thanks in advance.

You can change your code to:
DurationFormatUtils.formatDuration(millis, "mm:ss.SS");

to set the TImezone:
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
My Guess...if you are living in a GMT+30 min time zone and unless you specify a different one, your formatter will pick your current one, so it considers 0 hours as GMT and as you are in GMT+30 Min, it outputs + 30 Minutes...
To get timezone from user current place you can use:
TimeZone tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
then you can set the Timezone in dateformat.
it will return you the timezone like "IST"
Also you can try the following code to find the GMT offset of a Timezone:
public String getCurrentTimezoneOffset() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = "GMT"+(offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
it will return Timezone like: GMT+05:30 this format
By using timezone you can find accurate time in all devices..
see this also:https://developer.android.com/reference/java/util/TimeZone.html

Related

How to get the timezone offset in android?

I found some similar questions, such as:
How to get the timezone offset in GMT(Like GMT+7:00) from android device?
How to find out GMT offset value in android
But all these answers(+12:00) are incorrect for New Zealand Daylight Saving Time now.
When I did debug, I got this from Google Calendar event object:
"dateTime" -> "2016-11-06T10:00:00.000+13:00"
So how to get the correct offset which should be +13:00?
Thanks.
To get the current offset from UTC in milliseconds (which can vary according to DST):
return TimeZone.getDefault().getOffset(System.currentTimeMillis());
To get a RFC 822 timezone String instead, you can simply create a SimpleDateFormat instance:
return new SimpleDateFormat("Z").format(new Date());
The format is (+/-)HHMM
So, I tried to get gmt offset through Calendar and SimpleDateFormat but both returns 0. I found the solution using deprecated methods in Date class.
So, this code works for me.
private double getOffset() {
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
int defHour = calendar.get(Calendar.HOUR_OF_DAY);
int defMinute = calendar.get(Calendar.MINUTE) + (defHour * 60);
Date date = new Date(System.currentTimeMillis());
int curHour = date.getHours();
int curMinute = date.getMinutes() + (curHour * 60);
double offset = ((double) curMinute - defMinute) / 60;
return offset > 12? -24 + offset : offset;
}
Then you can format a result
This code return me GMT offset.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);
It returns the time zone offset like this: +0530

TimeZone offset shows invalid value

Unless I do something wrong...
I live in Poland (GMT+2). By the time I write this we are in daylight saving time. The following code, however, says that the GMT time offset is only 1 hour instead of 2.
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
System.out.println(mTimeZone);
int mGMTOffset = mTimeZone.getRawOffset();
System.out.printf("GMT offset is %s hours", TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));
prints GMT offset is 1 hours
Same happens for other timezones, for example New York, which is GMT-4:
Calendar mCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
prints GMT offset is -5 hours
There are two methods the TimeZone you have to use:
you can check if the a date is in DaylightSaveTime with:
mTimeZone.inDaylightTime(date)
And if this is True you have to add the value of
mTimeZone.getDSTSavings()
to the Offset:
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
System.out.println("TimeZone: "+mTimeZone);
int mGMTOffset = mTimeZone.getRawOffset();
if (mTimeZone.inDaylightTime(mCalendar.getTime())){
mGMTOffset += mTimeZone.getDSTSavings();
}
System.out.printf("GMT offset is %s hours",
TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));
output:
GMT offset is 2 hours
Check whether DST is active in java .
TimeZone tz = TimeZone.getTimeZone("America/New_York");
boolean inDs = tz.inDaylightTime(new Date());
Below code give you with DST time
TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);
System.out.println(format.format(new Date()));

Java - Convert From A Timezone Different From Local To UTC

So from all the posts I read about this issue (for example, Convert timestamp to UTC timezone).
I learn that a way to do this conversion is :
SimpleDateFormat dfmaputo = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
dfmaputo.setTimeZone(TimeZone.getTimeZone("UTC"));
long unixtime = dfmaputo.parse(data.get(1)).getTime();
unixtime = unixtime / 1000;
output:
original date (Maputo Timezone) -- 11/5/2015 1:39:45 PM
unix timestamp in UTC --- 1446687585
data.get(1) is the string with the maputo datetime.
I don't understand why I'm not getting the UTC value. When I convert the unix timestamp, that I was expecting to be in UTC, I get the original datetime with Maputo Timezone.
Am I missing something?
Do I need to convert first to my local timezone and than to UTC?
EDIT: Solution
Calendar maputoDateTime = Calendar.getInstance(TimeZone.getTimeZone("Africa/Maputo"));
maputoDateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
Long unixtimeGMT = maputoDateTime.getTimeInMillis() / 1000;
Instead of SimpleDateFormat I should use Calendar.
First I needed to set the input date's timezone (Africa/Maputo) and then set it to the one I needed (GMT). And only then I could get the correct unix timestamp.
Thanks to #BastiM reply in How to change TIMEZONE for a java.util.Calendar/Date
Thank you for your replies and help.
What if you add CAT timezone identifier to the end of string and formatter mask has z letter? If thats what you always get and source data does not give timezone value.
String sdt = "11/5/2015 11:39:45 PM CAT";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a z", Locale.US);
Date dt = sdf.parse(sdt);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(dt.getTime());
System.out.println(dt + ", utc=" + dt.getTime());
System.out.println(cal);

Covert date time from one zone to another

This is continuation to one of my previous question where I am not able to parse the date which is resolved now. In the below code, I have a date string and I know the time zone for the date string even though the string itself doesn't contain it. Then I need to convert the date into EST time zone.
String clientTimeZone = "CST6CDT";
String value = "Dec 29 2014 11:36PM";
value=StringUtils.replace(value, " ", " ");
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma").withZone(DateTimeZone.forID(clientTimeZone));
DateTime temp = df.parseDateTime(value);
System.out.println(temp.getZone().getID());
Timestamp ts1 = new Timestamp(temp.getMillis());
DateTime date = temp.withZoneRetainFields(DateTimeZone.forID("EST"));//withZone(DateTimeZone.forID("EST"));
Timestamp ts = new Timestamp(date.getMillis());
System.out.println(ts1+"="+ts);
When I am running the code I am expecting ts1 to remain same and ts to be up by 1 hr. But iam getting below which I don't understand. I thought EST is one hour ahead of CST and so if it is 11 in CST, it should be 12 in EST. Also there seems to be offset by about eleven and half hours. Any clues on what I am missing.
2014-12-30 11:06:00.0=2014-12-30 10:06:00.0
I think the below code will help you.
String clientTimeZone = "CST6CDT";
String toStimeZone = "EST";
String value = "Dec 29 2014 11:36PM";
TimeZone fromTimeZone = TimeZone.getTimeZone(clientTimeZone);
TimeZone toTimeZone = TimeZone.getTimeZone(toStimeZone);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(fromTimeZone);
SimpleDateFormat sf = new SimpleDateFormat("MMM dd yyyy KK:mma");
Date date = sf.parse(value);
calendar.setTime(date);
System.out.println(date);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Copied from : http://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/
The method withZoneRetainFields() preserves the fields in the timezone CST (= UTC-06) hence your local timestamp (as LocalDateTime) but combines it with a different timezone (EST = UTC-05) which is one hour ahead in offset and result in a different instant. You should it interprete it this way: The same local time happens one hour earlier in New York compared to Chicago.
The rule is to subtract positive offsets and to add negative offsets in order to make timestamp representations of instants comparable (normalizing to UTC offset).
Alternatively: Maybe you don't want this but want to preserve the instant instead of the local fields. In this case you have to use the method withZone().
Side notice: Effectively, you compare the instants represented by the variables temp and date and finally use your default timezone to print these instants in the JDBC-escape-format (explanation - you implicitly use Timestamp.toString()). I would rather recommend to use a dedicated instant formatter for this purpose or simpler (to have the offsets in focus):
System.out.println(temp.toInstant() + " = " + date.toInstant());

Get timzone compared to GMT in Android

I need to get the mobile TimeZone comparing to GMT in Android. I only could see one function returns that but as String:
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
tz.getID();
This is the description of getID():
Returns the ID of this TimeZone, such as America/Los_Angeles, GMT-08:00 or UTC.
The problem is I need to get that as Integer like +3, -5...
You should be able to calculate the difference based on the TimeZone getOffset() value, see http://developer.android.com/reference/java/util/TimeZone.html#getOffset(long)
public static String getCurrentTimezoneOffset() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
Use TimeZone.getOffset. Be aware that the time difference can change due to daylight saving time and that can widely vary per country and day of year. You should therefore not rely on that offset number throughout the year. Instead it is more reliable to use the TimeZone identifier instead.

Categories

Resources