Use time zone of device [duplicate] - java

This question already has answers here:
Getting device's local timezone
(4 answers)
Closed 9 years ago.
In my app i want to get the time zone of device and then use it in simple date format, here is my code:
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") ;
sdf.setTimeZone(tz);
i am getting correct id and display name from tz but the code does not works correctly for time.

you should use TimeZone.getDefault()
it returns a TimeZone based on the time zone where the program is running.

You are setting the TimeZone of the SimpleDateFormat so that it prints out a time in your local timezone, but the 'Z' at the end prints out a literal letter Z, which means UTC. You should remove the quotes around it so that it prints the actual timezone at the end, e.g. +0100.
That said, you haven't mentioned whether you're using the SimpleDateFormat for printing or for parsing.

Related

SimpleDateFormat with timezone displaying dates in my timezone, how do I fix this? [duplicate]

This question already has answers here:
SimpleDateFormat returns wrong time zone during parse
(2 answers)
SimpleDateFormat parse loses timezone [duplicate]
(3 answers)
DateFormat parse - not return date in UTC
(1 answer)
Get date from device and convert it to GMT+4
(1 answer)
Closed 3 years ago.
Given these two date Strings, I am trying to create a menu that allows you to select from the two dates (these are returned from an API with the users timezone):
2019-12-20T00:00:00.000-05:00
2019-12-19T00:00:00.000-05:00
I use the following code to parse the date string in the users preferred timezone (I have downloaded this locally to their devices). I have verified that the TZUtils.getUsersTimeZone() returns this timezone: America/New York which has an offset of -5.
fun getDateForString(date: String): Date {
val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
parser.timeZone = TZUtils.getUsersTimeZone()
return parser.parse(date)
}
When these dates are parsed, they are parsed into my local time time (offset -6) and not in the users local time zone (-5), even though I specify to use the users local time zone. When I create the popup menu, I used the following code to show the dates
public String getStringForDate(Date date) {
DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
return dateFormat.format(date);
}
And this returns me the wrong dates to select from (the dates are based on my timezone and not the users). Furthermore, when I select the data from the menu, the function I use to filter data based on if it is the same day as the selected date doesn't work because it uses my timezone as well. How do I fix this or do I just "assume" this will work for users since their devices are in their timezones?
You can use the modern java.time package instead and specially ZonedDateTime that handles time zones.
String str = "2019-12-20T00:00:00.000-05:00";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(str);
And when showing it in the UI use DateTimeFormatter to convert it to a formatted string
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
or with some custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
which will give you for the 2 formats
System.out.println(formatter.format(zonedDateTime));
2019-12-20T00:00-05:00
2019-12-20 00:00
SimpleDateFormat.getDateInstance(...) will give you an instance in the JVM's default time zone.
Set the time zone to whatever you need it to be.
DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
dateFormat.setTimeZone(/* whatever */);
return dateFormat.format(date);

How to get calender date from a date field in Java in a particular time zone? [duplicate]

This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 7 years ago.
I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format. Now if I try to get the calendar day (i.e. 04 april 2015) it gets converted to my local timezone and prints the next day(i.e 05 april 2015). How do I get the calendar day in a particular time zone (say +1:30 GMT)?
I am using the getdate()function from java.util.Date to get the calendar day.
I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format.
No, you have a Date variable. That doesn't have any particular format. Ignore what toString() tells you - that's just formatting it in your local time zone, in a default format. That doesn't mean the format or time zone is part of the state of the Date object - that just represents a point in time.
It sounds like you want:
// Whatever pattern you want - ideally, specify the locale too
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Whatever time zone you want
format.setTimeZone(...);
String text = format.format(date);
Alternatively, if you just want a Calendar value:
TimeZone zone = ...; // Whatever time zone you want
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
// Now use calendar.get(Calendar.YEAR) etc

How to convert String to date using Java in UNIX environment [duplicate]

This question already has answers here:
java.text.ParseException: Unparseable date
(10 answers)
Closed 8 years ago.
I am trying to convert a String ("01-OCT-2014") into Date format.
Below is my code for this.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date d= formatter.parse("01-OCT-2014");
System.out.println("Converted date:"+d);
The above code is working fine in Windows.
But when I am running in Unix environment, it is throwing an exception Unparseable date
Can any one help me out in solving this issue..
I suspect the problem is simply that your Unix environment isn't running in an English locale - so when it tries to parse the month name, it's not recognizing "OCT" as a valid value.
I would suggest using code like this:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Date d = formatter.parse("01-OCT-2014");
System.out.println("Converted date: " + d);
You might also want to specify the time zone of the formatter - if you're just parsing a date, then using UTC would make sense. Note that your output will use the system local time zone, because you're using Date.toString() - that doesn't mean that the Date has any notion of the time zone in its data; a Date is just a point in time.

How to convert a data from 1 timezone to another timezone? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Timezone conversion
I have a date in UTC, how to convert it to other timezone?
java.util.Date
Despite what the output of Date.toString() suggests, Date instances are not timezone aware. They simply represent a point in time, irrespective to the timezone. So if you have a Date instance, there is nothing more you need to do. And what if you have time in one time zone and you want to know what is the time in other time zone? You need
java.util.Calendar
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Tokyo"))
cal.set(Calendar.HOUR_OF_DAY, 15) //15:00 in Tokyo
cal.set(Calendar.MONTH, Calendar.NOVEMBER)
cal.setTimeZone(TimeZone.getTimeZone("Australia/Melbourne"))
cal.get(Calendar.HOUR_OF_DAY) //17:00 in Melbourne
Note that after changing the time zone the date (point in time) didn't changed. Only the representation (current hour in this particular time zone). Also note that November is important there. If we change the month to July suddenly the hour in Melbourne changes to 16:00. That's because Tokyo does not observe DST, while Melbourne does.
java.text.DateFormat
There is another catch in Java with time zones. When you are trying to format a date you need to specify time zone explicitly:
DateFormat format = DateFormat.getTimeInstance
format.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"))
Otherwise DateFormat always uses current computer's time zone which is often inappropriate:
format.format(cal.getTime())
Since format() method does not allow Calendar instances (even though it accepts Object as a parameter - sic!) you have to call Calendar.getTime() - which returns Date. And as being said previously - Date instances are not aware of time zones, hence the Tokyo and Melbourne settings are lost.
You can try Joda-Time library. They have 2 functions called withZone() and withZoneRetainFields() to perform timezone calculations.

Android get Current UTC time [duplicate]

This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 9 years ago.
What is the function to get the current UTC time. I have tried with System.getCurrentTime but i get the current date and time of the device.
Thanks
System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
Also see this related question.

Categories

Resources