How to get local time Android - 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);

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

Android timezone issue, confused

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

How to parse Date format server format To "MM/dd/YYYY"

I was found many solution but its not working for me.
I am trying to parse date to user selected date format.
I was getting date from server in this format 2016-06-30T00:00:00Z UTC Timezone
Now I want to Parse it in User selected format for e.g MM/dd/yyyy
How Can i do that.? I was found many solution but its not working for me.
To get date into a particular format, first you have to parse the date string into it's given format and there you will get Date object. Second, you can convert the date object into a desired format.
private String getFormattedDate(String strDate) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date d= (Date)formatter.parse(strDate);
SimpleDateFormat fmtOut = new SimpleDateFormat("MM/dd/yyyy");
return fmtOut.format(date);
}
This function help to convert any type of string date in any formate
public String getFormatedDate(String dateString, String format, String currentFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(currentFormat, Locale.ENGLISH);
try {
Date date = sdf.parse(dateString);
String formated = new SimpleDateFormat(format).format(date);
return formated;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

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

Date format to match the Date format in Phone Settings

I have a string which returns the date and time as 2012-11-08 12:45:30 . I need to get the date and time in separate strings and then the date has to be shown in the format which is there in the Phone's Date and Time settings.
Here is the code which I have tried so far:
date value from db is 2012-11-08
I am getting the date format in phone's settings as
String datefrmt = Settings.System.getString(
context.getContentResolver(), Settings.System.DATE_FORMAT);
the code to apply this format to the obtained date from db is:
SimpleDateFormat sdf = new SimpleDateFormat(datefrmt);
java.util.Date date_1 = sdf.parse("2012-11-08");
String s = sdf.format(date_1);
I am getting the month and day properly but the year its returning something randomly and thats not a correct value. Can anyone please guide me where am I going wrong. Thanks
If you have 2012-11-08 12:45:30 string and you want to parse it to Date object and change its format to another (system format for example or 2012-11-08 format):
try {
String yourString="2012-11-08 12:45:30";
//first we parse input date string and create Date object
String inputDateString ="yyyy-dd-MM hh:mm:ss";
SimpleDateFormat inputDateFormat = new SimpleDateFormat(inputDateString);
java.util.Date date = inputDateFormat.parse(yourString);
//log
Log.e(getClass().getName(), inputDateFormat.format(date));
//create system date format
String dateformt = Settings.System.getString( this.getContentResolver(), Settings.System.DATE_FORMAT);
//if its for some reason==null let it be "yyyy-dd-MM"
if(dateformt==null){
dateformt="yyyy-dd-MM";
}
SimpleDateFormat systemDateFormat = new SimpleDateFormat(dateformt);
String outputString = systemDateFormat.format(date);
//log
Log.e(getClass().getName(), outputString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use the simpleDateFormat as:
SimpleDateFormat simpDate = new SimpleDateFormat(datefrmt,
Locale.ENGLISH);
String s = simpDate.format(new Date());
for reference, you can refer to developer site:
for more information refer this link
Since your DB date is in yyyy-MM-dd, don't use the dynamic format to get the date, otherwise it will crash(throw parse exception), instead use the static format as below to get the date. You may use the dynamic format to convert the string as below:
//use static format to convert into date from static formatted data in db
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date_1 = sdf1.parse("2012-11-08");//got the date
//use the dynamic format to convert into string
SimpleDateFormat sdf2 = new SimpleDateFormat(datefrmt);
String s = sdf2.format(date_1);
Since final String format = Settings.System.getString(getActivity().getContentResolver(), Settings.System.DATE_FORMAT);//may be NULL
So I customized my function as below for general purposes
#SuppressLint("SimpleDateFormat")
public String getCurrentShortDateFormat() {
final String[] SFs = new String [] {
"MM/dd/yyyy",
"dd/MM/yyyy",
"yyyy/MM/dd"
};
final Date date = new Date(24638400000L);//24638400000=Oct/13/1970; 0==Jan/1/1970
java.text.DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
String current = shortDateFormat.format(date);
SimpleDateFormat which = new SimpleDateFormat();
for (int i = 0; i < SFs.length; i++) {
which.applyPattern(SFs[i]);
if (which.format(date).compareTo(current)==0)
return SFs[i];
}
return null;
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "----- onResume.CurrentShortDateFormat-----" + getCurrentShortDateFormat());
}

Categories

Resources