How to get timezone in short in android - android

I am trying to display a timestamp as "Sat Dec xx ww:yy:zz IST YYYY".
When i run this code snippet in android device i get result as "Sat Dec xx ww:yy:zz GMT+05:30 YYYY".
Date dd = new Date();
String s = dd.toString();
The below snippet also gives the time in GMT+05:30 format.
String timeZone =
Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
TimeZone can be any of the zones as per mob. location. So hard coding doesn't make any sense.
How can i get the result in the desired format?

Use SimpleDateFormat to explicitly get "Sat Dec xx ww:yy:zz" part and "YYYY" part
Store them up in variables
get the time zone String using
String timeZone =
Calendar.getInstance().getTimeZone().getID();
then use
String.format("%s %s %s", firstPart, timeZone, yearPart);

Related

Showing correct time from Milliseconds with desired TimeZone

I'm developing an application which takes data from Google TimeZone API.
Simply I have time in milliseconds of desired place on Earth.
For Example : 1504760156000 it's showing Date time In London which is
Thu Sep 07 2017 09:55:56
As I'm in TimeZone +05:00 from UTC if I manipulate 1504760156000 these milliseconds it will show me whole date time like below:
Thu Sep 07 2017 09:55:56 GMT+0500 (Pakistan Standard Time)
but I want to show:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
The problem is: I have correct date and time for London but enable to show/change TimeZone without changing Time because Time is correct according to London.
UPDATED
After getting some comments. You are not getting me here in my example.
Suppose I am in Pakistan and Time here is 1:55 PM so I asked GOOGLE API via my application to tell me whats the time in London at moment. Google API tell me time in London is 1504760156000 (9:55 AM) in milliseconds if I convert these milliseconds to Date Object it will print out like below:
Date date =new Date(1504760156000)
Thu Sep 07 2017 09:55:56 GMT+0500 (Pakistan Standard Time)
It will manipulate it according to my Local TimeZone but I want results like below
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
Updated 2
I prepared timestamp in seconds in UTC as Google Time Zone API needed timestamp UTC in form of seconds
"https://maps.googleapis.com/maps/api/timezone/json?location="+Latitude +","+Longitude+"&timestamp="+currentTimeUTCinSeonds+"&key="API KEY"
Google API respond me with below JSON against London.
{
"dstOffset" : 3600,
"rawOffset" : 0,
"status" : "OK",
"timeZoneId" : "Europe/London",
"timeZoneName" : "British Summer Time"
}
According to Docs:
Calculating the Local Time
The local time of a given location is the sum of the timestamp
parameter, and the dstOffset and rawOffset fields from the result.
I Sum up result timestamp+rawoffset+dstoffset*1000='1504760156000' (at moment when I tried it)
Code from Project
Long ultimateTime=((Long.parseLong(timeObject1.getDstOffset())*1000)+(Long.parseLong(timeObject1.getRawOffset())*1000)+timestamp*1000);
timeObject1.setTimestamp(ultimateTime); //its Sime POJO object to save current time of queried Location
Date date=new Date(ultimateTime);
date1.setText("Date Time : "+date);
As I said I'm manipulating result in Local Time Zone so it gave me below result at that time:
Thu Sep 07 2017 09:55:56 GMT+0500 (Pakistan Standard Time)
But I knew API gave me correct time. The problem is Local offset from UTC . I just want to change GMT+0500 to GMT+0100
Timestamps represent an "absolute" value of a time elapsed since epoch. Your currentTimeUTCinSeconds, for example, represent the number of seconds since unix epoch (which is 1970-01-01T00:00Z, or January 1st 1970 at midnight in UTC). Java API's usually work with the number of milliseconds since epoch.
But the concept is the same - those values are "absolute": they are the same for everyone in the world, no matter where they are. If 2 people in different parts of the world (in different timezones) get the current timestamp at the same time, they'll all get the same number.
What changes is that, in different timezones, this same number represents a different local date and time.
For example, the timestamp you're using, that corresponds to Sep 7th 2017 08:55:56 UTC, which value is 1504774556 (the number of seconds since epoch). This same number corresponds to 09:55 in London, 13:55 in Karachi, 17:55 in Tokyo and so on. Changing this number will change the local times for everyone - there's no need to manipulate it.
If you want to get a java.util.Date that represents this instant, just do:
int currentTimeUTCinSeconds = 1504774556;
// cast to long to not lose precision
Date date = new Date((long) currentTimeUTCinSeconds * 1000);
This date will keep the value 1504774556000 (the number of milliseconds since epoch). This value corresponds to 09:55 in London, 13:55 in Karachi and 17:55 in Tokyo.
But printing this date will convert it to your JVM default timezone (here is a good explanation about the behaviour of Date::toString() method). When you do "Date Time : "+date, it implicity calls toString() method, and the result is the date converted to your default timezone.
If you want the date in a specific format and in a specific timezone, you'll need a SimpleDateFormat. Just printing the date (with System.out.println or by logging it) won't work: you can't change the format of the date object itself, because a Date has no format.
I also use a java.util.Locale to specify that the month and day of week must be in English. If you don't specify a locale, it'll use the system default, and it's not guaranteed to always be English (and this can be changed, even at runtime, so it's better to always specify a locale):
// use the same format, use English for month and day of week
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (zzzz)", Locale.ENGLISH);
// set the timezone I want
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
// format the date
System.out.println(sdf.format(date));
The output will be:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
Note that I don't need to manipulate the timestamp value. I don't use the google API, but I think their explanation is too confusing and the code above achieve the same results with less complication.
In your specific case, you can do:
date1.setText("Date Time : "+sdf.format(date));
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
To get a date from a timestamp, I use a org.threeten.bp.Instant with a org.threeten.bp.ZoneId to convert it to a timezone, creating a org.threeten.bp.ZonedDateTime. Then I use a org.threeten.bp.format.DateTimeFormatter to format it:
int currentTimeUTCinSeconds = 1504774556;
// get the date in London from the timestamp
ZonedDateTime z = Instant.ofEpochSecond(currentTimeUTCinSeconds).atZone(ZoneId.of("Europe/London"));
// format it
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss 'GMT'XX (zzzz)", Locale.ENGLISH);
System.out.println(fmt.format(z));
The output is the same:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
In your case, just do:
date1.setText("Date Time : "+fmt.format(z));

How To See If One Date Is Newer Than Another

Hello I think I have a very simple question but i'm having trouble figuring it out.
I Got the Date and Time In Android using this code
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
It gave me back this value
Apr 21, 2016 9:30:16 PM
how do I compare using to dates with that value so if I want to see if
Apr 21, 2016 9:30:16 PM
is newer or older than
Apr 21, 2016 9:35:16 PM
How would I check that Thanks
Attempt One
I Tried This
DateFormat format = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
Date fileDate = format.parse(date1);
DateFormat format2 = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
Date metaDate = format.parse(date2);
this the value for date 1 and 2 being
Apr 21, 2016 9:35:16 PM
But it threw a parse exception. I must use that value above so What do I Need to do so it doesn't break the code when it tries to parse the date
The easiest way is to use Date.before(), rather than comparing the strings. In fact its easier to convert the string back into a date than use the strings.

joda-time can't read Parse dateTime string

I'm having an issue with joda-time formatting a date time string that Parse (parse.com) has stored in an sqlite table.
Sqlite creation string: "createdDate date time"
Storing parse date into table: "insert... parseObject.getCreatedAt()"
If i then use a SQLite browser to inspect the table, I see the date stored like this:
Sat Jun 15 15:44:52 PDT 2013
So going along with that, I wrote the following to convert it back into a DateTime object to give to parse as part of a query to get items that are newer than the last inserted in my table:
DateTimeFormatter format = DatetimeFormat.forPattern("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'");
DateTime dt = formatter.parseDateTime(datahelper.getLastInsertDate(..));
The formatter is this way, because in Parse's databrowser, I can see dateTimes being stored like this:
2013-06-24T08:11:45.280Z
I get an ANR though, so I tried using the following formatter:
DateTimeFormatter format = DatetimeFormat.forPattern("EEE' 'MMM' 'dd' 'HH':'mm':'ss 'z'' 'YYYY");
DateTime dt = formatter.parseDateTime(datahelper.getLastInsertDate(..));
and I still get an ANR. The trace in eclipse shows the following:
Caused by: java.lang.IllegalArgumentException: invalid format: "Tue Jun 25 00:13:29 PDT 2013"
at org.joda.time.format.DateTimeFormatter.parseDateTime"
The second ANR trace shows:
Invalid format: "Tue Jun 25 00:13:29 PDT 2013" is malformed at "PDT
2013"
I've tried getting around that, as joda time does not parse "z" to PDT/PST, so I've put 'PDT' in my formatter to hopefully get it to work, but nothing seems to work.
Any ideas?
Edit 1: Using the accepted answer, I have a timezone formatting issue)
DateFormat originalFormat = new SimpleDateFormat("EEE MMM DDD HH:mm:ss z yyyy");
Date originaldate = originalFormat.parse(datahelper.getLastInsertdate);
Log.i("converted date: ", String.valueOf(originalDate);
Log.i("a real date: ", "String.valueOf(new Date(new Date().getTime)));
I get two outputs:
Fri Jan 25 15:14:11 PST 2013
Tue Jun 25 17:11:44 PDT 2013
why does the converted date show PST, and a standard Date shows PDT?
It seems to be a known problem Joda cannot parse Timezone names sadly. In the documentation before all the pattern syntaxes you will see this line:
The pattern syntax is mostly compatible with java.text.SimpleDateFormat - time zone names cannot be parsed and a few more symbols are supported. All ASCII letters are reserved as pattern letters, which are defined as follows:
You can see that in the documentation link here
Now the solution to your answer can be found in this answer by #BalusC located here
Hope this helps.
I think that with SQLite, because the date type is somewhat broken, the best thing to do is to store the long that you get from Date.getTime() or related Joda methods.
When you get the long from the database, re-construct your date object (e.g. new Date(long)), and then format that.
Above all, remember that (IMHO) the only sensible way to store a date is in reference to UTC, which is what you get with Date.getTime() and new Date(long) : milliseconds since Jan 1, 1970 UTC.
Once you retrieve your date, format it with whatever timezone is appropriate.

Getting timezone on android with respect to GMT

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

How to get time from SimpleDateFormate() in android?

I have a String this:-
Tue Oct 30 13:22:58 GMT+05:30 2012;
I want to divide time & date from SimpleDateFormate:-
DateFormat f = new SimpleDateFormat("EEE,MM/dd/yyyy hh:mm:ss);
Date d = f.parse(my string);
DateFormat date = new SimpleDateFormat("MM/dd/yyyy");
DateFormat time = new SimpleDateFormat("hh:mm:ss a");
System.out.println("Date: " + date.format(d));
System.out.println("Time: " + time.format(d));
I am getting this Error:-
java.text.ParseException: Unparseable date: "Tue Oct 30 13:22:58 GMT+05:30 2012"
Please Tell me whats the problem.
Thanks,
Deepanker
Your timestamp string does not match your pattern:
Tue Oct 30 13:22:58 GMT+05:30 2012
is no way like (not to mention syntax error in the SimpleDataFormat initialization line):
EEE,MM/dd/yyyy hh:mm:ss
So you need to make the pattern matching input data. All fields supported by SimpleDateFormat are described here.
Are you sure the date is correct??
because I tried to parse it
it gives error on GMT+05:30
just remove the :30 and it will work, see here:
String time = "Tue Oct 30 13:22:58 GMT+05 2012";
long f=Date.parse(time);
System.out.println("Time:" + f);
As it stands, your timezone offset does not match the RFC 822 standard, so I don't think you can directly parse the date without performing some cleansing on it first.
If you just want an offset, then the string should look like:
Tue Oct 30 13:22:58 +0530 2012
Note, there is no "GMT", and no colon within the offset. The corresponding pattern is then:
new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy")
Alternatively, you can specify the timezone:
Tue Oct 30 13:22:58 IST 2012
For which the pattern is:
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")

Categories

Resources