Getting timezone on android with respect to GMT - android

I want to get the timezone on an android device with respect to UTC. For example, if I'm in PST timezone, then I want it in this format: "-0800". Is it possible?

This snippet gives me PST timezone represented as "-0800", which is UTC representation for PST. It was just a matter of formatting. Thanks to SimpleDateFormat class.
Calendar cal = Calendar.getInstance(Locale.getDefault()); String
timezoneStr = new SimpleDateFormat("Z").format(cal.getTime());

Related

Convert indian time zone to local time

In my app I am getting time from server in API in IST timezone, I want to show time in device's local time zone.
Below is my code for this but it seems its not working.
SimpleDateFormat serverSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat utcSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
serverSDF.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
utcSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
localSDF.setTimeZone(TimeZone.getDefault());
Date serverDate = serverSDF.parse(dateString);
String utcDate = utcSDF.format(serverDate);
Date localDate = localSDF.parse(utcDate);
From server I am getting time "2018-02-28 16:04:12" in IST and the code above displays "Wed Feb 28 10:34:12 GMT+05:30 2018".
The other answer uses GMT+05:30, but it's much better to use a proper timezone such as Asia/Kolkata. It works now because India currently uses the +05:30 offset, but it's not guaranteed to be the same forever.
If someday the government decides to change the country's offset (which already happened in the past), your code with a hardcoded GMT+05:30 will stop working - but a code with Asia/Kolkata (and a JVM with the timezone data updated) will keep working.
But today there's a better API to manipulate dates, see here how to configure it: How to use ThreeTenABP in Android Project
This is better than SimpleDateFormat, a class known to have tons of problems: https://eyalsch.wordpress.com/2009/05/29/sdf/
With this API, the code would be:
String serverDate = "2018-02-28 16:04:12";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime istLocalDate = LocalDateTime.parse(serverDate, fmt);
// set the date to India timezone
String output = istLocalDate.atZone(ZoneId.of("Asia/Kolkata"))
// convert to device's zone
.withZoneSameInstant(ZoneId.systemDefault())
// format
.format(fmt);
In my machine, the output is 2018-02-28 07:34:12 (it varies according to the default timezone of your environment).
Although it seems complicated to learn a new API, in this case I think it's totally worth it. The new API is much better, easier to use (once you learn the concepts), less error-prone, and fix lots of problems of the old API.
Check Oracle's tutorial to learn more about it: https://docs.oracle.com/javase/tutorial/datetime/
Update: Check this answer by #istt which uses modern Java8 date-time api.
You don't need to change format in UTC first. You can simply use:
SimpleDateFormat serverSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
serverSDF.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
localSDF.setTimeZone(TimeZone.getDefault());
String localDate = localSDF.format(serverSDF.parse(dateString));

How to get current UTC or GMT date time in millis in android instead of getting device's current date 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 5 years ago.
I am trying to get current UTC date time in millis.
But every code I used for this returns me the device's current date time.
When I chenge my device's date, time it shows me chenged one.
So, I want to get GMT/UTC date time so that it will show me correct date even if user changes the date, time of his/her device.
Codes I tried:
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
and
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String gmtTime = df.format(new Date());
Date gmtDate = df.parse(gmtTime);
Actually I want to set an alarm at November 15 2017, 5 PM using AlarmManager, receive that event hide some activities in my app which I don't want to show after this date, time.
How can I acheive this?
Thanks in advance!
Use this ....
Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInM‌​illis()
for eg.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long timeInMili = calendar .getTimeInMillis();
or
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
long timeInMili = calendar .getTimeInMillis();
Try TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
long timestampMilliseconds =System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String stringDate = simpleDateFormat.format(new Date(timestampMilliseconds));
System.out.println(stringDate);
if do you want to get as utc just change the time zsone
There is no way to get the correct time from device independently, If you are using Google Location Provider then getTime() will return derived time from GPS signal, else use server time.

Converting milliseconds to Date object

I am having following code to convert milliseconds to Android Date object.
Date dateObj = new Date(milli);
But problem is that my milliseconds value is having GMT value added in it before i pass it to Date class, add when i print this date object i can see that date object is again adding GMT value in the milliseconds value and because of that my date is displayed as wrong.
So how can i generate Date object with out considering GMT value in it.
For example my milliseconds are 1385569800000 which is getting printed as below:
Wed, 27 Nov 2013 22:00:00 --> +5.30
But the current value of this time stamp without adding GMT is:
Wed, 27 Nov 2013 16:30:00
*UPDAE*
It is not just about printing the date in right format and with right date time.
But i want to use that date object to schedule TimeTask.
So basically i want to create Date object which has proper date time value in it with out adding extra GMT time added in it.
A Date is always in UTC. No need to change that.
When printing the date value, use SimpleDateFormat and call setTimeZone() on it before formatting the output string.
It is not just about printing the date in right format and with right date time.
But i want to use that date object to schedule TimeTask.
TimerTask is just a task and not its scheduling. Timer accepts a Date object for scheduling. The Date is in UTC there as well.
try my code if you a
long currentTime = System.currentTimeMillis();
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
currentTime -= offsetInMillis;
Date date = new Date(currentTime);
it is work for me
You can try with joda-time API.
Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.
http://joda-time.sourceforge.net/key_instant.html
A Date object simply represents a moment in time. Imagine you're on the phone to someone on a different continent, and you say "3...2...1...NOW!". That "NOW" is the same moment for both of you, even though for one person it's 9am and for the other it's 4pm.
You're creating a Date representing the moment 1385569800000 milliseconds after the Java epoch (the beginning of 1970, GMT). That is your "NOW", and it's fixed and unchanging. What it looks like converted into text, however, depends on which timezone you want to display it for. Java defaults to using GMT, which would be right if you were in Britain during the winter, but for (I'm guessing) India you want it in a different time zone. Laalto's answer shows you how to do that.
here is the code,that worked like charm for me:
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}

Get time of different Time zones on selection of time from time picker

I have an issue of converting selected hours and minutes to different time zones of countries.
Supposing if i select 10 am in India then i want to know at 10 am in india what will be the time in USA/New york and Tokyo.and Vice versa.
Any help is appreciable...
Thank you
please find the sollution below :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mma");
TimeZone timezone = TimeZone.getDefault();
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
Date d = new Date();
sdf.setTimeZone(timezone);
String strtime = sdf.format(d);
Log.e("str time gmt ",strtime);
sdf.setTimeZone(utcTimeZone);
strtime = sdf.format(d);
Log.e("str time utc ",strtime);
i think this will solve your problem
You can probably use Joda Time - Java date and time API. You can get the DateTimeZone depending on the Canonical ID defined in the Joda Time,
DateTimeZone zone = DateTimeZone.forID("Asia/Kolkata");
Joda Time has a complete list of Canonical ID from where you can get TimeZone depending on the Canonical ID.
So, if you want to get the local time in New York at this very moment, you would do the following
// get current moment in default time zone
DateTime dt = new DateTime();
// translate to New York local time
DateTime dtNewYork = dt.withZone(DateTimeZone.forID("America/New_York"));
For getting more idea you can refer Changing TimeZone
Try using Joda-Time library
check the org.joda.time.DateTimeZone class
Here is the API documentation for the same.
you can also get it using , Here no external API is needed
DateFormat format = new SimpleDateFormat("MMMMM d, yyyy, h:mm a");
TimeZone utc = TimeZone.getTimeZone("America/New_York");
System.out.println(utc.getID());
GregorianCalendar gc = new GregorianCalendar(utc);
Date now = gc.getTime();
System.out.println(format.format(now));
you can see more time zone on this Link
Output
America/New_York
December 29, 2012, 11:04 AM
If you don't know city name then you can also use it by Zone name as follow
DateFormat format = new SimpleDateFormat("MMMMM d, yyyy, h:mm a");
TimeZone cst = TimeZone.getTimeZone("US/Eastern");
System.out.println(cst.getID());
GregorianCalendar gc = new GregorianCalendar(cst);
Date now = gc.getTime();
format.setTimeZone(cst);
System.out.println(format.format(now))
Output
US/Eastern
December 29, 2012, 12:38 AM
Not really sure about the solution I'm going to provide but I think you can try it. GMT (Greenwich Mean Time) is a standard. I think you can keep it as a base and calculate the desired time. GMT standard is easily available too.
For example: While installing an OS like Windows XP or Windows 7, we select the time from a drop down menu. My point is, keeping this as the base, you can find the difference between the time zones in NY-US and Tokyo-Japan or vice versa as you desire it.
Hope this helps.

Converting date in string to specified locale on Android

I have this date in string:
"2011-08-28 08:30:00 +0000"
I want this to convert to a java.util.Date in hungarian Locale, so I try to use this formatter:
DateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", new Locale("hu"));
I am expecting that with currentDateFormat.parse I get "2011-08-28 10:30:00" as date (Hungary is GMT+2) but it is still "2011-08-28 08:30:00". I've tried to use setTimeZone(TimeZone.getDefault()) but didn't help.
Any ideas?
Android only uses UTC, no more GMT.
The problem is the date you have there is not clearly UTC and Android doesn't know what to do with it so it's default behavior is to just assume your date is in the current time zone.

Categories

Resources