Android timezone issue, confused - android

I have a date like this Tue Jun 21 14:47:37 GMT+05:30 2016 , which I create myself. I create it using calendar. Where user selects a date and I save it as milliseconds from calendar.
When I send it , send it, I again create a calendar instance put the saved milliseconds into it and get the date like this :
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(SSPreferences.getDate());
Now while getting date from calendar i do this :
calendar.getTime()//This is what I send to server.
I send it to server, but when server sends me the date, it is always 5.5 hours before my time.
I know my time is GMT+5:50. So what server is doing on its side ?
How do I send the date , such that I get back the same date which I sent to the server.
Any help is appreciated.
Thanks

check this
static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss"
public static Date GetUTCdatetimeAsDate()
{
//note: doesn't check for null
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}

Finally I solved the issue by adding/subtracting the rawOffSet from the local time zone.
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getOffset(SSPreferences.getDate());
WriteLog.Print("offset is "+offset);
long newtime = SSPreferences.getDate() + offset;
calendar.setTimeInMillis(newtime);

Related

Android - Getting different UTC time

I have two methods for get UTC date time.
method:1) get current UTC
public static String getUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
Log.e("utcTime : " ,""+ utcTime);
return utcTime;
}
which print below Log
utcTime : 2018-07-12- 12:37:09
method:2) select date from calendar and get UTC
public static String dateUTCToLocal() {
try {
SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy HH:mm:ss", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse("12/7/2018 06:07:09");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getDefault());
return format.format(value);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
which print below Log
2018-07-12- 11:37:09
Problem : getting different UTC date (1 hour different )not understand why i tried many solutions but not getting perfect result, any help appreciate thanks in advance.
Try this format ..
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss a", Locale.US);
it show time into am pm wise.
The line "format.setTimeZone(TimeZone.getDefault());" sets the timezone you are currently in while "sdf.setTimeZone(TimeZone.getTimeZone("UTC"));" sets the timezone to "UTC". You should stick with the second line if you want to get UTC-time

Timestamp to Date/Time

I am trying to make a football Livescore app. And I need to show the match time to users as their local match time.
if I was generated a Timestamp from a given timezone, lets say it is
autodatetime(1517009400,6.5); //original timezone included
//I can make it done in javascript by https://www.autodatetime.com/
But I was trying to get it from Android with this code
public String getconvertedtime(long timestamp) {
try{
Toast.makeText(getApplicationContext(),Integer.toString(TimeZone.getDefault().getDSTSavings()),Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
//getTimezonedifference() return 0 for me
timestamp= timestamp-getTimezonedifference();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, (tz.getOffset(calendar.getTimeInMillis())-tz.getDSTSavings()));
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date currentTimeZone = calendar.getTime();
return dateFormat.format(currentTimeZone);
}catch (Exception e) {
return "";
}
}
public int getTimezonedifference() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
double offsetInMillis = tz.getOffset(cal.getTimeInMillis());
//String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
//offset = "GMT"+(offsetInMillis >= 0 ? "+" : "-") + offset;
offsetInMillis= Math.abs((offsetInMillis)-(6.5*3600000));
int vall=(int)offsetInMillis;
return vall;
}
Unfortunately It was returning wrong time, I can't figure it out why it was showing faster hours .
The result is 01/27/2018 12:30:00 PM
It must be 01/26/2018 11:30:00 PM for my Local TimeZone(6.5)
And I found something about different DST problems from googling and get 0 from "TimeZone.getDefault().getDSTSavings()" on Toast.
Please guide me to the solution, I am new to android programming. Thank you for reading.
Given epoch of 1517009400, which is 01/26/2018 23:30:00 GMT, to show this time in user's local time:
// convert to epoch milli seconds
long ts = 1517009400000l;
Date date = new Date(ts);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String dateStr = dateFormat.format(date);
android.util.Log.i("TEST", "dateStr: " + dateStr);
dateStr will be formatted according to timezone of user's phone. For example, my phone is set to Asia/Kuala_Lumpur timezone, which is GMT+8, so it shows 01/27/2018 07:30:00.
To format date string into particular timezone (eg: New York), you can try this:
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String dateStr = dateFormat.format(date);
This outputs 01/26/2018 18:30:00.

How to get user's timezone and convert time saved in database according to the user's timezone? Please see details

I'm developing an app in which I'm saving the time when the post was posted.
I'm getting that time by using this code:
DateFormat currentTime = new SimpleDateFormat("h:mm a");
final String time = currentTime.format(Calendar.getInstance().getTime());
Now, what I want is I want to get user's timezone and convert the time saved in database using his/her timezone to his/her local time.
I tried doing this using code:
public String convertTime(Date d) {
//You are getting server date as argument, parse your server response and then pass date to this method
SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a");
String actualTime = sdfAmerica.format(d);
//Changed timezone
TimeZone tzInAmerica = TimeZone.getDefault();
sdfAmerica.setTimeZone(tzInAmerica);
convertedTime = sdfAmerica.format(d);
Toast.makeText(getBaseContext(), "actual : " + actualTime + " converted " + convertedTime, Toast.LENGTH_LONG).show();
return convertedTime;
}
but this is not changing the time.
This is how I'm trying to convert time saved in database using above method (postedAtTime is the time which is getting retrieved from database):
String timeStr = postedAtTime;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
Date date = null;
try {
date = df.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
convertTime(date);
Please let me know what's wrong in my code or if this is wrong way?
The time string you're storing is not sufficient to be able to change timezones after the fact (h:mm a is only hours, minutes and am/pm marker). In order to do something like this you need to either store the timezone the original timestamp was in or better yet store the time in a deterministic manner like always UTC.
Example code:
final Date now = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
// Convert to UTC for persistence
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Persist string to DB - UTC timezone
final String persisted = sdf.format(now);
System.out.println(String.format(Locale.US, "Date is: %s", persisted));
// Parse string from DB - UTC timezone
final Date parsed = sdf.parse(persisted);
// Now convert to whatever timezone for display purposes
final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US);
displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
final String display = displayFormat.format(parsed);
System.out.println(String.format(Locale.US, "Date is: %s", display));
Output
Date is: 2016-06-24 17:49:43
Date is: 13:49 PM -0400

How to get local time Android

I have a String of a date and time in my app eg:- 2014-10-30T11:30:00 I want to convert this String into my local time which should look something like this
2014-10-30T11:30:00+05:30. I cannot Manipulate the String as the server side conversion is done to do the addition and subtraction of the time. How do I add the +05:30 offset to my time?
How can I do it using the local time so that the server knows my locale?
Try this way,hope this will help you to solve your problem.
How to use given function :
convertDateStringFormat("2014-10-30T11:30:00","yyyy-MM-dd'T'hh:mm:ss","yyyy-MM-dd'T'hh:mm:ss")
Here you have pass three parameter as :
1.strDate : which is represent datetime string.
2.fromFormat : which is represent datetime format of your given datetime string.
3.toFormat : which is represent datetime format which you wan to convert your given datetime string.
public String convertDateStringFormat(String strDate, String fromFormat, String toFormat){
try{
SimpleDateFormat sdf = new SimpleDateFormat(fromFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.trim());
return dateFormat2.format(sdf.parse(strDate));
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);
long timestamp = cursor.getLong(columnIndex);
Log.d("Server time: ", timestamp);
String localTime = sdf.format(new Date(timestamp * 1000));
Log.d("Time: ", localTime);

How to post dateTime to soap webservice from android

When I post the datestring to server, the time always changes. How can I post the datestring in soap webservices.
<Validfrom>dateTime</Validfrom>
I convert the string to date object, it posted but the time changes.
plz help me anyone to me
private Date getDateObj(String dateInString) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date = null;
try {
System.out.println(dateInString);
date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Above code represents my date object and I posted data like:
request.addProperty(name.trim(),
getDateObj(value));
Actually you have to calculate server time like GMT because your location is India (according to stack overflow profile). So, you are in +5.30 GMT. That's why you are getting wrong time from server with India time. So, use my code that will give you GMT server time :)
Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
date.setTimeZone(TimeZone.getTimeZone("UTC-06"));
String localTime = date.format(currentLocalTime);
may thz will help u
best of luck dude

Categories

Resources