I m trying to get time from one zone say IST OR ANY other time zone then convert it to GMT TIME zone string. But when I try to get timestamp from GMT based string time I get local timestamp value. Any specific reason why so.
Found this on web.
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");
calendar.setTimeZone(fromTimeZone);
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());
"Any specific reason why so?" Yes, because Java assumes that by default you want to "print out" (render) date values in the local timezone where the JVM is running.
#Before
public void setup() {
sdf = new SimpleDateFormat(Hello.TS_FORMAT);// TS_FORMAT = "yyyyMMdd'T'HHmmssXX";
Calendar cal = sdf.getCalendar();
cal.setTimeZone(TimeZone.getTimeZone(UTC_TIME_ZONE));// UTC_TIME_ZONE = "GMT";
sdf.setCalendar(cal);
...
}
#Test
public void testTimestampFormat03() {
String inboundTimestampText = '20170322T170805-0700';// means inbound is in Pacific Time Zone (17:08:05 on 03/22)
Date dt = sdf.parse(inboundTimestampText);
String defaultFormat = dt.toString();// default locale is Central Time Zone (19:08:05 on 03/22)
String actualFormat = sdf.format(dt);
String expectedFormat = inboundTimestampText.replace('T17', 'T00');
expectedFormat = expectedFormat.replace('0322', '0323');// expected Time Zone is UTC (00:08:05 on 03/23)
expectedFormat = expectedFormat.replace('-', 'Z');
assertEquals(expectedFormat, actualFormat + '0700');
}
You have to specify the timezone you want the date value to "render" in. Basically, you need to use "the same" formatter to print out the date formatter.format(aDate) that you used to read in the date string formatter.parse(aDtaeString).
Related
This question already has answers here:
How to set time zone of a java.util.Date?
(12 answers)
Closed 5 years ago.
I have a dates stored in mysql with no timezone, like 2001-01-10 00:00:00.
I have tomcat running in timezone +10:00 for example.
I need to generate a Date() that have no offset int the object.
If I do this:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime( new Date(/*from 2001-01-10 00:00:00*/) );
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date newDate = cal.getTime();
The result Date object still having the zoneinfo and zoneoffset reporting to server timezone, not UTC.
I need to generate a Date() Object that have ZERO TIME, but mantain the date stored in mysql, independent of tomcat timezone.
In other words, I want to generate date with zero hour/min/sec independent of server timezone.
The date generated shows 2001-01-01T00:00:00.000+1400
the time is zero but offset is +14:00.
I want to generate 2001-01-01T00:00:00.000+0000
The mysql datatime is DATETIME
The Date object does not keep timezone information, imagine it as a class with only a long property which stores the number of milliseconds that passed from 1970.
The SimpleDateFormat class or other libraries like JODA are responsible of keeping track of timezone when they transform the date to string.
The date itself doesn't have any time zone. Its toString() method uses the current default time zone to return a String representing this date, as explained in this post. However, you can precise the target timezone during the formatting, to obtain the desired result:
// 2001-01-01T00:00:00.000+00:00
long timestamp = 978307200_000L;
Date newDate = new Date(timestamp);
SimpleDateFormat u = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
u.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat k = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
k.setTimeZone(TimeZone.getTimeZone("Pacific/Kiritimati"));
assertEquals("2001-01-01T00:00:00.000+0000", u.format(newDate));
assertEquals("2001-01-01T14:00:00.000+1400", k.format(newDate));
Well, the only way that I can acquire desired result, is making an adjust to Java Date, I get the current offset of Tomcat and add/remove him from the Date, the follow function make the date returned by rest is allways the same, independent of the tomcat timezone. I use JODA DateTime for this.
public Date adjustDateTimeZoneToUTC( Date date )
{
Date utcDate = null;
if( date != null )
{
int curOffset = TimeZone.getDefault().getRawOffset();
DateTime dt = new DateTime(date).withZoneRetainFields(DateTimeZone.UTC);
// Se o offset for NEGATIVO(-12:00), deve-se somar esse tempo
// Se o offset for POSITIVO(+12:00), deve-se subtrair esse tempo
if( curOffset >= 0 ) {
dt.minusMillis(curOffset);
} else {
curOffset *= -1;
dt.plusMillis(curOffset);
}
utcDate = dt.toDate();
}
return utcDate;
}
On the client side, using angular datepicker or other javascript calendar, you need to do the same way on javascript, for you date stay imutable on different timezones. Like the sample:
$dateParser.timezoneOffsetAdjust = function (date, timezone, undo) {
if (!date) {
return null;
}
// Right now, only 'UTC' is supported.
if (timezone && timezone === 'UTC') {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + (undo ? -1 : 1) * date.getTimezoneOffset());
}
return date;
};
I want to calculate Relatives Date which is how many days different from 01/01/1957 to a given date. I need handle Daylight saving at the same time. Here is the code:
public String convertToRelative(String endDate) throws ParseException {
String relativeDate;
String baseDate = "19570101";
boolean isDST = TimeZone.getDefault().inDaylightTime(new java.util.Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(baseDate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(endDate));
long time2 = cal.getTimeInMillis();
if ( isDST ) {
long between_days = (time2 - time1 - 3600000)/(1000*3600*24);
int relative = Integer.parseInt(String.valueOf(between_days));
relativeDate = String.valueOf(relative + 1);
} else {
long between_days = (time2 - time1)/(1000*3600*24);
int relative = Integer.parseInt(String.valueOf(between_days));
relativeDate = String.valueOf(relative + 1);
}
return relativeDate;
}
From the code, you can see I checked if the time is in daylight saving at:
boolean isDST = TimeZone.getDefault().inDaylightTime(new java.util.Date());
But it only gets default time from the system. My question is how can I check the given date is a daylight saving date first then do the calculation part. I'm using New Zealand time zone. Thank you.
Rather than doing the calculations manually, you should try to take advantage of the built-in API of java.time which are easy to use and take care of DST for you.
Refer : https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#until-java.time.temporal.Temporal-java.time.temporal.TemporalUnit-
The following code should help you with calculations you are trying to do:
ZoneId auckZone = ZoneId.of("Pacific/Auckland");
LocalDateTime base = LocalDate.of(1957, 01, 01).atStartOfDay();
ZonedDateTime baseDate = base.atZone(auckZone);
ZonedDateTime endDate = LocalDate.parse(endDt, DateTimeFormatter.ofPattern("yyyyMMdd")).atStartOfDay().atZone(auckZone);
System.out.println(baseDate.until(endDate, ChronoUnit.DAYS));
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
My Date format is like as "MM-dd-yyyy hh:mm" its not current date ,I have to send this date
to server but before send it need to change this date to GMT format but when I change by following code:
private String[] DateConvertor(String datevalue)
{
String date_value[] = null;
String strGMTFormat = null;
SimpleDateFormat objFormat,objFormat1;
Calendar objCalendar;
Date objdate1,objdate2;
if(!datevalue.equals(""))
{
try
{
//Specify your format
objFormat1 = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
objFormat1.setTimeZone(Calendar.getInstance().getTimeZone());
objFormat = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
objFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
//Convert into GMT format
//objFormat.setTimeZone(TimeZone.getDefault());//);
objdate1=objFormat1.parse(datevalue);
//
//objdate2=objFormat.parse(datevalue);
//objFormat.setCalendar(objCalendar);
strGMTFormat = objFormat.format(objdate1.getTime());
//strGMTFormat = objFormat.format(objdate1.getTime());
//strGMTFormat=objdate1.toString();
if(strGMTFormat!=null && !strGMTFormat.equals(""))
date_value = strGMTFormat.split(",");
}
catch (Exception e)
{
e.printStackTrace();
e.toString();
}
finally
{
objFormat = null;
objCalendar = null;
}
}
return date_value;
}
its not change in required format ,I have tried by above code first try to get current timeZone and after that try change string date into that timezone after that convert GMT.
anyone guide me.
thanks in advance.
Try the below code. The first sysout prints the date object which picks up default OS timezone i.e. IST in my case. The second sysout prints the date in the required format after converting the date to GMT timezone.
If you know the timezone of your date string then set that in the formatter. I assumed you need the same date format in the GMT timezone.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
Date date = format.parse("01-23-2012,09:40");
System.out.println(date);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(date));
you need to use TimeZone's getRawOffset() method:
Date localDate = Calendar.getInstance().getTime();
TimeZone tz = TimeZone.getDefault();
Date gmtDate = new Date(date.getTime() - tz.getRawOffset());
it
returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.
If you want to consider DST as well (you might want this ;-) )
if (tz.inDaylightTime(ret)) {
Date dstDate = new Date(gmtDate.getTime() - tz.getDSTSavings());
if (tz.inDaylightTime(dstDate) {
gmtDate = dstDate;
}
}
The last check is needed if you are right on the edge of a summer time change and would, for instance, go back into standard time by the conversion.
Hope that helps,
-Hannes
my code computes the date and time correctly including the dayLightSaving time,when run on my local server from india. But when I run the same code from US server I am getting the time which is one hour ahead for the timeZoneId which is not abserving DST.
TimeZone tz = TimeZone.getTimeZone("America/Phoenix");
Date currTime = getDateByTZ(new Date(), tz);
System.out.println("currTime" + currTime);
public static Date getDateByTZ(Date d, TimeZone tz) throws Exception {
if (tz == null) {
tz = TimeZone.getDefault();
}
Integer tzOffSet = tz.getRawOffset();
Integer tzDST = tz.getDSTSavings();
Integer defOffSet = TimeZone.getDefault().getRawOffset();
Integer defDST = TimeZone.getDefault().getDSTSavings();
Calendar cal = Calendar.getInstance(tz);
cal.setTime(d);
if (tz.inDaylightTime(d)) {
cal.add(Calendar.MILLISECOND, -defOffSet);
cal.add(Calendar.MILLISECOND, -defDST);
cal.add(Calendar.MILLISECOND, +tzOffSet);
cal.add(Calendar.MILLISECOND, +tzDST);
} else {
cal.add(Calendar.MILLISECOND, -defOffSet);
cal.add(Calendar.MILLISECOND, tzOffSet);
}
return cal.getTime();
}
Results from Localserver:
currTime:Mon Oct 22 01:52:21 IST 2012
Results from USserver:
currTime:Mon Oct 22 02:52:21 IST 2012
This code doesn't make much sense. A Date object doesn't have to be transformed to be used in another time zone. It represents a universal instant.
What makes sense is to use the time zone when displaying (or formatting as a string) a Date object. In this case, you should simply set the time zone on the DateFormat instance, and the universal instant that constitutes a date will be formatted in order to make sense for the given time zone.
Date now = new Date(); // now, whatever the timezone is
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getDefault());
System.out.println("Now displayed in the default time zone : " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Now displayed in the New York time zone : " + df.format(now));