Print a UTC time in my local timezone - java

I have a timestamp coming from an API in this format:
yyyy-MM-dd'T'HH:mm:ss.SSSSSS
I want to format it for the user in their own timezone (on android). This is what I'm doing:
String timestampFromApi = "...";
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
Date date = df1.parse(timestampFromApi);
DateFormat df2 = new SimpleDateFormat();
Log.v(TAG, "In your timezone: " + df2.format(date));
But this prints the time in UTC. For example, if the timestamp happened at 4pm UTC time, and I am in PDT, the result is that it still prints "4pm".
I checked the timezone being used:
df2.getTimeZone()
and it does print out PDT for my device. What have I done wrong here?
Thanks

You're on the right track. You got the UTC time from the server, but now you just need to calculate the local offset when formatting. Try something like this:
private String formatTime(String timestampFromApi){
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
df1.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df1.parse(timestampFromApi);
Log.v(TAG, "In your timezone: " + df1.format(getAdjustedTime(date.getTime())));
}
private Date getAdjustedTime(long utcDate){
return new Date(utcDate + TimeZone.getDefault().getOffset(new Date().getTime()));
}
The getAdjustedTime() method will create a new Date object based on the UTC-offset from the local TimeZone.

Related

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);

Fast way to parse a Long date into Month-Day-Year String

How do you parse a Long date like: 1366222239935 into a String of space-separated Month-Day-Year? Like into "Apr 18 2013"
Passing it on a java.util.Date and to a String will give a String of date which contains so many info that I don't need for rendering in my GWT application.
Need to do this style since I will be passing the result into 3 <span> elements; so actually the space-separated date will be split into parts:
Month
Day
Year
As gwt won't support SimpleDateFormat
instead use Gwt DateTimeFormat
DateTimeFormat f = DateTimeFormat.getFormat("dd-MMM-yyyy");
String datestring =f.format(dateGeneratedbyLong);
And make sure the DateTimeFormat import also which you can use both client and server side .
There is another class with same name but package is different which is client(restricts you to use on client side only )
try to use SimpleDataFormat check http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html>
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
String dateAsString = simpleDateFormat.format(new Date());
You could convert it to a Date and then manually build your String like this.-
Date date = new Date(timeInMils);
String res = date.get(Calendar.MONTH) + " " +
date.get(Calendar.DAY_OF_MONTH) + " " +
date.get(Calendar.YEAR);
That Long number is simply the number of milliseconds since the JavaScript epoch (1/1/1970 at midnight, UTC time). So, instead of parsing it, use the constructor for the Date object:
var myDate = new Date(1366222239935);
alert(myDate);
That will show "Wed Apr 17 2013 11:10:39 GMT-0700 (Pacific Daylight Time)". I am in PST, but it will default to whatever timezone you have in your locale settings.
Inside a GWT app in Java, simply do:
Date date=new Date(1366222239935);
Then you can use SimpleDateFormat to render it as "dd/MM/yy".
See http://www.w3schools.com/jsref/jsref_obj_date.asp
Do like this
Date d = new Date();
d.setTime(1366222239935l);
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd yyyy");
try {
System.out.println(sdf.format((d)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = 1366222239935l;
Date date = new Date(diff);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println(sdf.format(date));

How to convert "MM-dd-yyyy hh:mm" String date format to GMT format?

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

Parsing formatted Date String in another TimeZone to date object not working

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.

Java convert date to EST timezone to respecting DST

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);

Categories

Resources