I want to get a Date Object in UTC Time Zone so i am converting it first to a String which is returing me correct UTC Date String but when i am again parsing it to Date object then Local Time Zone String(ie. IST) is getting appended in that Date instead of UTC.
Date date = new Date();
DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String estTime = timeFormat.format(date);
date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(estTime);
A Date doesn't have a timezone, it represents a moment in time. It holds the time in milliseconds.
You can't have a Date with a format, it doesn't work that way. If you need to show the Date in a GUI, console or anywhere else, that's when you use a SimpleDateFormat like you did to change it to a String in the format you want.
Related
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);
I want to convert this incoming date "962409600000" to date.I first tried to convert it to datetime format "2000-07-01T05:45:00.000+05:45" and then convert it to 2000-07-01.But I am successful to convert to datetime format.Please help me how ca I do that.
Thanks
First parse the String to Long format
Long inComingDate = Long.parseLong("962409600000");//parse the string to long
Construct the Date object and format it using SimpleDateFormat
Date date = new Date(inComingDate); //Convert the java.util.Date
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); //convert it format you desire
String dateInString = format.format(date);
Well to get it as a Date, just use:
Date date = new Date(962409600000L);
If you want that as a string representation, use:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String text = format.format(date);
Note the part setting the time zone to UTC - the value you've given is midnight UTC on July 1st. If you apply the default time zone, you'll end up with the day before anywhere which is behind UTC in summer time.
I am trying to convert a formatted date String to Date object. Date String is formatted to some other timezone.
When I do sdf.parse(String) it returns me my System date object.
Code is as below,
static Date convertGMTTime(String timeZone, long longDate){
Date convertedTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
Date date = new Date(longDate);
System.out.println("timezone: "+timeZone +", timestamp: "+date);
Locale locale = Locale.ENGLISH;
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
/* DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(destTimeZone);*/
sdf.setTimeZone(destTimeZone);
String convertedDateStr = sdf.format(date);
System.out.println("convertedDateStr: "+convertedDateStr);
convertedTime = sdf.parse(convertedDateStr);
System.out.println("convertedTime: "+convertedTime + "sdf: "+sdf.getTimeZone());
}catch(Exception e){
e.printStackTrace();
}
return convertedTime;
}
I would appreciate if anyone could help and point out where I am going wrong.
Thanks in advance.
Output:
timezone: Atlantic/Cape_Verde, timestamp: Tue Jun 26 17:38:11 IST 2012
Source timezone: sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
convertedDateStr: 2012-06-26 11:08:11
convertedTime: Tue Jun 26 17:38:11 IST 2012
sdf:sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Some more details to share, When I use another sdf object(without setting timezone for it), It do return me correct time and date but still timezone is picked from System clock
Code
static Date convertGMTTime(String timeZone, long longDate){
Date convertedTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdfParse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
Date date = new Date(longDate);
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
sdf.setTimeZone(destTimeZone);
String convertedDateStr = sdf.format(date);
System.out.println("convertedDateStr: "+convertedDateStr );
convertedTime = sdfParse.parse(convertedDateStr,new ParsePosition(0));
System.out.println("convertedTime: "+convertedTime + "sdf: "+sdf.getTimeZone());
}catch(Exception e){
e.printStackTrace();
}
return convertedTime;
}
Output
Source timezone: sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
convertedDateStr: 2012-06-26 12:24:56
convertedTime: Tue Jun 26 12:24:56 IST 2012
sdf: sun.util.calendar.ZoneInfo[id="Atlantic/Cape_Verde",offset=-3600000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
I understand that when I do not assign timezone to sdf it takes System time zone, but why doesn't it show time in System time zone? I shows it in timezone as it was in String but Timezone is different.
Ans when I set timezone it returns date object as per my system time irrespective of the fact that sdf has some other time zone set.
Can anyone please explain the functional behavior for sdf.parse and sdf.format.
For me sdf.setTimeZone() does have its impact when we use format and it is nullified when we use sdf.parse(). I find it quite strange.
Appreciate help in this regard.
You already have a Date (or the number of milliseconds of the Date), so there is nothing to convert. A Date doesn't have any time zone. It's a universal instant in time. The time zone is relevant only when you display this date, because the date 65647678000 could be 12:38 in some time zone, but 10:38 in some other time zone. It's also relevant when you parse the String representation of a Date, because 10:38 is 65647678000 in some time zone, but is 65657678000 in some other.
While you don't display a Date object, or parse a String to a Date, you don't need to care about time zones. And to choose the time zone used when displaying/parsing it, set the time zone of the DateFormat, and then use DateFormat.format()/DateFormat.parse() to format/parse the date.
When you use Date.toString() to display a date, it will always use your current time zone.
I find it easier to understand what I mean by not thinking of a Date as a day, a month, a year, an hour, etc., but as a moment: "when Kennedy was shot". "When Kennedy was shot" is the same moment for everyone. But if you represent the moment "when Kennedy was shot" in Dallas time zone, it's not the same result as the result you get when you represent this same moment in Paris time zone.
I want to get the current date converted to America/Montreal timezone. I'm doing it like this:
Date date = new Date();
TimeZone timeZone = TimeZone.getTimeZone ("America/Montreal");
Calendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
String whatIWant = "" + cal.get(Calendar.HOUR_OF_DAY) + ':'+
cal.get(Calendar.MINUTE)+ ':'+ cal.get(Calendar.SECOND);
log.info(whatIWant);
The conversion is just fine but I was wondering how robust this code is. What will happen when in no daylight saving?
That code is fine. Java automatically takes winter time or summer time into account.
You could also do this by using a DateFormat object to convert the date to a string, setting the desired time zone on the DateFormat object:
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
// Tell the DateFormat that you want the time in this timezone
df.setTimeZone(TimeZone.getTimeZone("America/Montreal"));
String whatIWant = df.format(date);
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("PST"));
cal.setTime(new Date());
System.out.println("cal:"+cal);
System.out.println("cal.getime:"+cal.getTime());
output are:
cal:java.util.GregorianCalendar[time=1325177592164,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="PST",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=PST,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2011,MONTH=11,WEEK_OF_YEAR=53,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=363,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=53,SECOND=12,MILLISECOND=164,ZONE_OFFSET=-28800000,DST_OFFSET=0]
cal.getime:Thu Dec 29 22:23:12 IST 2011
Problems facing:
While print 'cal' object getting date and time as per time zone.
cal.getTime() not displaying date and time to as per timezone.
You should represent time in UTC (java.util.Date) and then display the time in the local timezone of the user. Use DateFormat and TimeZone to do that. Read this article for more details
Unfortunately Date object always display time in GMT. You need to use something like SimpleDateFormat to display time in formatted timezone.
assign user given time into string variable then create date formatter. then parse the given string using date formatter.
String dateAndTime = "30-12-2011 12:00:00 GMT+5.30"; dateFormate
formate = new SimpleDateFormate("dd-mm-yyyy hh:mm:ss z"); Date date =
formate.parse(dateAndTime );
Date object is Java doesn't store the TimeZone info.
If you do
new Date()
this is the current local time of the machine/jvm.
To print it with the default/local timezone info:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
System.out.println(sdf.format(new Date()));