How to find out the values of GMT for user for example it is +05:30 for India.
How do calculate this +05:30 value in Android ?
I need this because I am using a java library in my app which has a function with this +05:30 field and I want to generate this field by calculation so that I wont have to fill up individual values for countries.
This is what works awesome
public double getOffset(){
TimeZone timezone = TimeZone.getDefault();
int seconds = timezone.getOffset(Calendar.ZONE_OFFSET)/1000;
double minutes = seconds/60;
double hours = minutes/60;
return hours;
}
First get the epoch system time
System.currentTimeMillis()
Then use a date object, set the time zone to GMT and initialize with the long valye
dateObj.setTimeZone(TimeZone.getTimeZone("GMT"))
To get time in GMT use below function where dateInString is the value of date,and format is date format as yyyyMMddHH
public static long getDate(String dateInString,String format){
long date = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = dateFormat.parse(dateInString);
date = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Use below method to get UTC :-
public int GetUnixTime()
{
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
int utc = (int)(now / 1000);
return (utc);
}
after you get UTC now compared it to the Epoch in this site http://www.xav.com/time.cgi.
see this below link :-
How can I get the current date and time in UTC or GMT in Java?
If you store a map between timezones and their GMT offsets in your app, you can call TimeZone.getDefault() to get the device's timezone and do a quick lookup to return the GMT offset. That way you don't have to rely on potentially tricky date/time calculations and can be sure you have the correct value.
Related
I'm trying to convert this time stamp value to date but its giving me wrong time. date is correct
TimeStamp : 1423821615
True Value : Fri, 13 Feb 2015 10:00:15 GMT
Android Code shows : Fri, 13 Feb 2015 15:30:15 IST
Here is the code I'm using to convert time stamp to date.
Date dt = new Date((long)timestampInSeconds * 1000);
I tried this code too but same result
public static Date getDateFromTimeStamp(long timestampInMilliseconds) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestampInMilliseconds);
return cal.getTime();
}
Date dt = getDateFromTimeStamp((long)timestampInSeconds * 1000);
I don't know what I'm doing wrong. Please help
Now I explain the whole scenario. My client is from UK and I'm from India (+5:30 ahead). He created appointment for 10 AM in UK obviously. But now I have his database in my local PC. My .NET software it shows same time as it shows in below image of SQL server. But in mobile, it doesn't. PC and mobile both are in same time zone.
I use this code to convert date to time stamp and send this time stamp to mobile app through web service
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, Appointments.DateTime) AS AppointmentTimeStamp FROM Appointments
Here is image of what my .NET software displays
does it matter that record was created when database was in UK time zone. Or I'm still doing a mistake somewhere.
I didn't understand what you wanna get.
If you get time as EPOCH time, you don't have information about time zone where this time stamp was made. So, you should know time zone offset and + or minus this seconds from this time stamp.
But I think the best way to use ISO 8601 format for time stamp, it's easy to convert to any timezone what you need
for example, this code convert ISO data to local time or return current time depends on locale timezone
private long time2LocalTimeZone (String date){
//"2016-07-29T23:07:45.120+00"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
try {
return sdf.parse(date).getTime();
} catch (ParseException e){
return (new Date()).getTime();
}
}
this code count your offset from GMT timezone and convert to epoch time depends on locale timezone
private long time2LocalTimeZone (long date){
TimeZone tz = TimeZone.getDefault();
Date now = new Date();
int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
return date + offsetFromUtc;
}
I want convert data like 2016-4-10 00:00:00 to timestamp.
I use this code (I send this date as argument to this method):
public static long parseUTimeAndGiveTimestamp(String time) {
if (time != null && !time.equals("")) {
long longTime = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS");
Date date;
try {
time += ".000";
date = sdf.parse(time);
} catch (Exception e) {
e.printStackTrace();
return longTime;
}
longTime = date.getTime();
return longTime / 1000;
}
return 0;
}
But I get 1460235600 value and if I convert it to date again I get:
Sat, 09 Apr 2016 21:00:00
(before 10.04 - after 09.04)
So you can help me?
There is no issue with your code. There is some issue with the timezones. Your SimpleDateFormat will be using your local timezone. You probable might be getting the timestamp for your locale and while converting it back to the date, you are checking in GMT timezone. To test this just add
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
before parsing the date.
So basically you are not using the same timezones to convert date to timestamp and while converting timestamp to zone.
try to use one M to parse single-digit month format. It also handles two-digits correctly...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd kk:mm:ss.SSS");
I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.
I am working on timezones concept in Android.
I want to change the timezone of the Android tablet by taking the timezone from the App Variable in the application. I am getting the System TimeZones as the variable value i.e like
Dateline Standard Time
UTC-11
Samoa Standard Time
Hawaiian Standard Time
Alaskan Standard Time
Pacific Standard Time (Mexico)
Pacific Standard Time
US Mountain Standard Time
Mountain Standard Time (Mexico)
Mountain Standard Time
Central America Standard Time
Central Standard Time
Central Standard Time (Mexico)
Canada Central Standard Time
SA Pacific Standard Time
From Android case, I am getting Timezone Id's like
Africa/Harare
Africa/Johannesburg
Africa/Kigali
Africa/Lubumbashi
Africa/Lusaka
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Tripoli
Asia/Amman
Asia/Beirut
Asia/Istanbul
Asia/Jerusalem
Asia/Nicosia
Asia/Tel_Aviv
CAT
EET
Egypt
Etc/GMT-2
Europe/Chisinau
Europe/Helsinki
and my code is
if (mCalendar != null) {
mCalendar = Calendar.getInstance();
}
else
{
String[] allTimeZones = TimeZone.getAvailableIDs();
Arrays.sort(allTimeZones);
for (int i = 0; i < allTimeZones.length; i++) {
System.out.println(allTimeZones[i]);
}
TimeZone tz = TimeZone.getTimeZone(String.valueOf(Jordan Standard Time));
mCalendar = Calendar.getInstance(tz);
String name = tz.getID();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " + name);
}
As 'Jordan Standard Time' is variable from application is not like Timezone of tablet available Id's, Timezone is not changing.
If I replace the Timezone with 'Africa/Tripoli' manually, the timezone is replacing with this one.
My issue now is I would like to convert the system timezones to Tablet Timezone Ids and display it in Android Application.
plz use this function that is display GMT Time display if you change timezone from you android phone.
public static String GetDateForGMTDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-mm-dd");
SimpleDateFormat formatter1 = new SimpleDateFormat(
"yyyy-mm-dd");
Date date = null;
try {
date = formatter.parse(dateString);
System.out.println(date);
System.out.println(formatter.format(date));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Log.i("Time zone", "gettime=" + cal.getTime());
cal.add(Calendar.MINUTE, (-1 * getTimeZoneDifference()));
Log.i("Time zone", "after gmt +gettime=" + cal.getTime());
date = cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return formatter1.format(date);
}
public static final int getTimeZoneDifference() {
long currentTime = System.currentTimeMillis();
int gmtcurrentOffset = TimeZone.getDefault().getOffset(currentTime);
int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
int minuteDifference = (((gmtOffset - gmtcurrentOffset) / 1000) / 60);
return minuteDifference;
}
use 1st function and pass any date with yyy-mm-dd formate as a string. and that function will return gmt formate real date-time.
i already use it.
its working fine.i hope its useful to you.
I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas
To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}