code for converting GMT to device time zone not working - java

I have a time input in the following format from a RSS feed:
Wed Jun 13 17:05:44 +0000 2012
and I need output as Wed Jun 13, 2012 22:35:44
The source time will be always in GMT, and the required output time will be in the device time zone(it may be GMT+5:30 or GMT-2:00 or any).
So firstly I have an calendar instance with GMT, as follows.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Then modified the calendar like following using StringTokenizer on input time.
calendar.set(Calendar.DAY_OF_MONTH, date);
calendar.set(Calendar.MONTH, month);
.
.
etc.
Next I have the following code:
calendar.setTimeZone(TimeZone.getDefault());
Basically the above code changes a calendar into device time zone.
Now the matter is the above code is working fine in normal environment, but not working in Android.
Any solution? Please help.

First you required DateFormat to parse string value in Date object and then you can set Timezone in Date as well as you can make Calendar object with help of Date that calendar object will be your device timezone instance.
Below code is working at my side
String input_format = "EEE MMMMM dd HH:mm:ss Z yyyy";
String input_value="Wed Jun 13 17:05:44 +0000 2012";
Date date=null;
SimpleDateFormat sdf = new SimpleDateFormat(input_format);
try {
date = sdf.parse(input_value);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = sdf.getCalendar();
calendar.setTime(date);

if i understand it right, you just want to set the timezome
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setTimeZone("Europe/Paris");
this for example set the timezone to Paris

Related

SimpleDateFormat results in incorrect time

I have the following code
protected void amethod1() {
String strDate = "Thu May 18 16:24:59 UTC 2017";
String dateFormatStr = "EEE MMM dd HH:mm:ss zzz yyyy";
DateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
Date formattedDate = null;
try {
formattedDate = dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
The resulting value of formattedDate is- "Thu May 18 11:24:59 CDT 2017" .
I am testing this code in Chicago and the local timezone is CDT.
I am not able to understand why the time value changes from 16:24:59 to 11:24:59 even though. Am I missing something in the defined format of the date?
Class Date doesn't contain any timezone at all. It's just a number of milliseconds since 01.01.1970 00:00:00 GMT. If you try to see, what formattedDate contains with System.out.println or debugger, you'll get formatted date for your local timezone. 11:24:59 CDT and 16:24:59 UTC are the same time, so result is correct.
Is java.util.Date using TimeZone?
It is better to use jodatime or Java 8 Time API in order to better manage time and timezones.
First, you are getting the correct time. When Daylight Savings Time is in use in Chicago (which it is on May 18), the time is 11:24:59 when it’s 16:24:59 in UTC. So your Date value represents the same point in time. This is all you can expect from a Date.
I understand that you want not just a point in time, but also the UTC time zone. Since Axel P has already recommended Java 8 date and time API, I just wanted to fill in the details:
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern(dateFormatStr, Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse(strDate, parseFormatter);
The result is
2017-05-18T16:24:59Z[UTC]
If you always want the UTC time zone, the Instant class is just right for it, so you will probably want to convert to it:
Instant instant = dateTime.toInstant();
Instants are always in UTC, popularly speaking.
SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now=new Date();
System.out.println(myFmt.format(now));
I hope I can help you. If you can,please adopt.Thank you
The resulting value of formattedDate is- "Thu May 18 11:24:59 CDT 2017" . Why? because your time zone running -5 hour from UTC time you will find in below link wiki time zone abbreviations, if you want result in same timezone you need to specify timezone in formater Hope you get my concern
https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
public static void amethod1() {
String strDate = "Thu May 18 16:24:59 UTC 2017";
String dateFormatStr = "EEE MMM dd HH:mm:ss zzz yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date formattedDate = null;
try {
formattedDate = dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("formattedDate: "+dateFormat.format(formattedDate));
}
You specified timezone, that's why after parsing time on current timezone (where you are), SimpleDateFormat sets UTC timezone. When you try to output your date, it is displayed on your current timezone
It appears you would need to specify the TimeZone as well when you format the Date For eg. .TimeZone.setDefault(TimeZone.getTimeZone("PST"));
Have a look at this discussion TimeZone
The output of a Date depends on the format specified, where you can specify the timezone, as shown in the example below:
protected void amethod2() {
String strDate = "Thu May 18 16:24:59 UTC 2017";
String dateFormatStr = "EEE MMM dd HH:mm:ss zzz yyyy";
DateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
Date formattedDate = null;
try {
formattedDate = dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Date: " + formattedDate);
// Thu May 18 17:24:59 BST 2017, BST is my system default timezone
// Set the time zone to UTC for the calendar of dateFormat
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Date in timezone UTC: " + dateFormat.format(formattedDate));
// Thu May 18 16:24:59 UTC 2017
// Set the time zone to America/Chicago
dateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println("Date in timezone America/Chicago: " + dateFormat.format(formattedDate));
// Thu May 18 11:24:59 CDT 2017
}
As for the IDs, such as "UTC" and "America/Chicago" in the example, you can get a complete list of them via TimeZone.getAvailableIDs(). You can print them out to have a look:
Arrays.stream(java.util.TimeZone.getAvailableIDs()).forEach(System.out::println);
And you'll have:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
...

How to convert date object to ones own timezone in android?

In android, I download date information from a MySQL database on a free web server, then convert it to a Date object using:
Note: the server time is 5 hours ahead of toronto.
public static Date getDateFromSQLDate(String sqldate) {
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = (Date) formatter.parse(sqldate);
TimeZone targetTimeZone = TimeZone.getDefault();
TimeZone serverTimeZone = TimeZone.getTimeZone("Europe/London");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeZone(serverTimeZone);
calendar.add(Calendar.MILLISECOND, serverTimeZone.getRawOffset() * -1);
if (serverTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, targetTimeZone.getRawOffset());
if (targetTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, targetTimeZone.getDSTSavings());
}
return calendar.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
This doesn't seem to work..
The problem is that the date is relative to the timezone of the server. The one downloading could be confused with the times as they don't know its not in their own timezone.
I have a Date object, is there a way I can retrieve the timezone of the location the users phone is in, and then modify that Date object to be their own timezone?
Thanks
EDIT:
How to get TimeZone from android mobile?
This gets a timezone object, but how do I change a Date object with it?
My app has to deal with server time similar to you.
(All datetime that I got from server represent datetime at UTC +00:00)
// date string to convert
String dateString = "2014-01-07 12:00:00"
// create date formatter, set time zone to UTC and parse
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
TimeZone serverTimeZone = TimeZone.getTimeZone("UTC");
formatter.setTimeZone(serverTimeZone);
Date date = formatter.parse(dateString);
Log.i("Debug", "date object : " + date.toString());
// I'm in Bangkok (UTC +07:00) so I'll see "Wed Jan 07 19:00:00 GMT+07:00 2015"
// If you do this in Toronto, you should see "Wed Jan 07 07:00:00 GMT -05:00 2015"
When you wanna print this date in Toronto, I believe you don't have to calculate DST by yourself because calendar and date formatter should handle that (not sure, I read from somewhere long ago)
// Create timezone for Toronto
TimeZone torontoTimeZone = TimeZone.getTimeZone("America/Toronto");
// Create calendar, set timezone, to see hour of day in Toronto
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(torontoTimeZone);
calendar.setTime(date);
Log.i("Debug", "Hour of day : " + calendar.get(Calendar.HOUR_OF_DAY);
// Hour of day : 7
// Create date formatter, set timezone, to print date for Toronto user.
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy, hh:mm", Locale.US);
formatter.setTimeZone(torontoTimeZone);
String torontoDate = formatter.format(date);
Log.i("Debug", "Date in Toronto : " + torontoDate);
// Date in Toronto : 07 Jan 2015, 07:00
You can set calendar and date formatter to user timezone by replace
TimeZone timezone = TimeZone.getTimeZone("America/Toronto")
with
TimeZone timezone = TimeZone.getDefault()
When I deal with date from server, I'll
request UTC time from server, if server doesn't send me UTC time, convert to UTC time first.
when parse date object from server, I always create date object represent time at UTC (time at server)
perform calculation or anything else with UTC date object.
pass only UTC date object from and to Activity/Fragment/Service/Model
only format date string with user timezone only when I need to display to user.
This is how you can change the date to your timezone
SimpleDateformat sdf = new SimpleDateFormat("yourformat");
TimeZone tz = TimeZone.getDefault();
sdf.setTimezone(tz);
sdf.format(yourdate); //will return a string in "your-format" to represent date
You're on the right track. You need to set the time zone of the Calendar object to the server's time zone. Then you can add the offset (and factor in DST) with the TimeZone that you got from the user's device (the link you included).
Code:
calendar.add(Calendar.MILLISECOND, serverTimeZone.getRawOffset() * -1);
if (serverTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, targetTimeZone.getRawOffset());
if (targetTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, targetTimeZone.getDSTSavings());
}
After that, you can retrieve the date in the usual way from the Calendar.
Also see this answer for more information.

how can i get current system date in Android?

I am getting date in 28/12/2013 format, but I need current date in a String format,
like
Thursday, August 21
so that I can set over TextView,
Explain a bit, if you think something is necessary, I am new to Android Development.
You can always refer to the documentation.
http://developer.android.com/reference/java/util/Date.html
In the documentation you will find this:
Calendar.get(Calendar.MONTH)
public int getMonth () #old do not use
Returns the gregorian calendar month for this Date object.
Calendar.get(Calendar.YEAR
public int getYear () #old do not use
Returns the gregorian calendar year since 1900 for this Date object.
Calendar.get(Calendar.DAY_OF_WEEK)
public int getDay () #old do not use
Returns the gregorian calendar day of the week for this Date object.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMM dd");
String formatedDate = sdf.format(your_date);
At the moment I haven't programmed any android app, I'll do that in the future. But I have found that here. It may soulve your problem hopefully.
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateInstance(),
DateFormat.getDateTimeInstance(),
DateFormat.getTimeInstance(),
};
for (DateFormat df : formats) {
System.out.println(df.format(new Date(0)));
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(new Date(0)));
}
Produces this output when run on an en_US device in the America/Los_Angeles time zone:
Dec 31, 1969
Jan 1, 1970
Dec 31, 1969 4:00:00 PM
Jan 1, 1970 12:00:00 AM
4:00:00 PM
12:00:00 AM

How to get Current Date using GMT in android?

I want Current Date in GMT wise Timezone.I used following code.
public static Date getGMTDate(String dateFormat) throws ParseException
{
SimpleDateFormat dateFormatGmt = new SimpleDateFormat(dateFormat);
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
// Local time zone
SimpleDateFormat dateFormatLocal = new SimpleDateFormat(dateFormat);
// Time in GMT
return dateFormatLocal.parse(dateFormatGmt.format(new Date()));
}
//call above function.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = getGMTDate("yyyy-MM-dd HH:mm:ss");
when i will change my device date then time is display in GMT formate but Date is not display in GMT timezone.its display of device's date.
but I want Current GMT Date.
This may works
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(new Date())+"");
Specify the format, and you will get it in GMT!
EDIT: You can also check This
I changed your method as below
public static String getGMTDate() {
DateFormat dateFmt = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM);
dateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
// Time in GMT
return dateFmt.format(new Date());
}
And got the following date (which is same as what you wanted I believe)
07-18 10:41:54.525: D/test(6996): GMT Date is: **Jul 18, 2013 10:41:03 AM**
So simply call this method and it will return the GMT date in string format.
EDIT 1:
you are setting GMT time zone and not GMT Date. You are not trying to understand your code. When you called new Data() it returned your device date, and then you formatted it for the corresponding GMT date and time. So if your change your device date to 16th July then your code (or even my code) will return the GMT equivalent of 16th July time. If you want 18th July GMT time even when your device's date is 16th July 2000, then I don't think you can do it without getting it from some network entity.
EDIT 2:
You should look at this SO reference to a similar kind of problem and it may serve you well.
Output: 2016-08-01 14:37:48 UTC
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Works fine.

Java: Iteration of given Dates

I have two dates in Java:
Wed Jan 05 00:00:00 CET 2011
Sat Jan 15 23:59:59 CET 2011
Now I want to iterate over them, so that every day I can do a System.out.println() in which I put the date in this kind on the console:
2011-01-05
2011-01-06
2011-01-07
...
2011-01-13
2011-01-14
2011-01-15
How can I do this?
Best Regards, Tim.
Update:
Calendar calend = Calendar.getInstance();
calend.setTime(myObject.getBeginDate());
Calendar beginCalendar = new GregorianCalendar(calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DATE));
calend.setTime(myObject.getEndDate());
Calendar endCalendar = new GregorianCalendar(calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DATE));
while (beginCalendar.compareTo(endCalendar) <= 0) {
// ... calculations
beginCalendar.add(Calendar.DATE, 1);
}
Use the GregorianCalendar object to increment one day at a time
Output using SimpleDateFormat.
To get your date from a string, into a Date object, you have to do the following
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = format.parse(yourDateString);
Then, you need to convert into a GregorianCalendar, so that you can easily increment the values and finally output the date using another SimplerDateFormat in the way you want to. See the documentation for the different codes.
Update:
Update, following your code update, you can simply do the following
Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(myObject.getBeginDate());
Calendar endCalendar = Calendar.getInstance();
beginCalendar.setTime(myObject.getEndDate());
while (beginCalendar.compareTo(endCalendar) <= 0) {
// ... calculations
beginCalendar.add(Calendar.DATE, 1);
}
Create a Calendar object and set it at the start date. Keep adding a day at a time and printing until you're at the end date.

Categories