How to convert time as per Timezone selection in android? - android

My Application downloading shopping details.
Example :
Shopping details downloaded at 5 :30 London time.
Now, change any other timezone, so convert downloaded time s per the selected timezone.
Timezone is changing from settings under Date/time.
How to programmatically achieve this ?
so how to convert the downloaded time as per the timezone selection ?

Try this,
I assume you have downloaded the shopping details at 12:00 PM London time. I am using HH assuming that you are using 24hr format. If you want to convert that to device default time zone, set the timezone using DateFormat & format the existing time.
TimeZone.getDefault() which gives the device default timezone.
try {
DateFormat utcFormat = new SimpleDateFormat("HH:mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = utcFormat.parse("12:00");
DateFormat deviceFormat = new SimpleDateFormat("HH:mm");
deviceFormat.setTimeZone(TimeZone.getDefault()); //Device timezone
String convertedTime = deviceFormat.format(date);
} catch(Exception e){
}

no, there are no APIs for changing time or timezone.. It is not possible to change the phone's timezone programmatically.

Based on #Raghavendra solution, this can be a portable method as follows:
/**
* converts GMT date and/or time with a certain pattern into Local Device TimeZone
* Example of dateTimePattern:
* "HH:mm",
* "yyyy-MM-dd HH:mm:ss",
* "yyyy-MM-dd HH:mm"
* Ex of dateTimeGMT:
* "12:00",
* "15:23",
* "2019-02-22 09:00:21"
* This assumes 24hr format
*/
#SuppressLint("SimpleDateFormat")
private String getDeviceDateTimeFromGMT(String dateTimePattern, String dateTimeGMT) {
try {
DateFormat utcFormat = new SimpleDateFormat(dateTimePattern);
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // convert from GMT TimeZone
Date date = utcFormat.parse(dateTimeGMT);
DateFormat deviceFormat = new SimpleDateFormat(dateTimePattern);
deviceFormat.setTimeZone(TimeZone.getDefault()); // Device TimeZone
return deviceFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Usage:
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm", "2019-02-22 16:07");
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm:ss", "2019-02-22 16:07:13");
getDeviceDateTimeFromGMT("H:mm", "16:07");

Related

DateTime Local time zone to UTC and UTC to some other selected timezone conversion in Android

I am developing an android application. In my app I stored my logged-in local date time in preference and showing in the user profile page. After some of days I changed my mobile timezone as Australia. Now I need to convert my existing local date time to Australia timezone date time and display in profile page. Is it possible. Show me the code snippet. Your help will be appreciated. Thanks in advance.
String inputText = "2017-05-17 15:50:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
SimpleDateFormat outputFormat =
new SimpleDateFormat("MMM dd, yyyy h:mm a");
// Adjust locale and zone appropriately
Date date = null;
try {
date = df.parse(inputText);
} catch (ParseException e) {
e.printStackTrace();
}
String outputText = outputFormat.format(date);
System.out.println(outputText);
Try this code.. it may help

Convert the Time from time zone -500 to the device located time zone

I have the datetime in the format like
2016-12-26 02:54:20 -0500
Now I need to convert this time to the device located time format.
If the device used in the Singapore then the time should convert automatically to the Singapore time zone, if device is in India then automatically it should convert to Indian time zone.
Please help to get the solution, Thanks in advance.
Use this method
public String convertTimeZone(String date) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
inFormat.setTimeZone(TimeZone.getDefault());
Date toConvert = inFormat.parse(date);
date = inFormat.format(toConvert);
return date.toString();
}

Trying to parse a date throws parser error

Im trying to parse date of type 23-May-2016 and 24-May 2016 for instance..
Following code demonstrates how im parsing the date.
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
Date validityDate = null;
Date nextDueDate = null;
try {
validityDate = format1.parse(mValidityDate.getText().toString());
nextDueDate = format1.parse(mNextDueDate.getText().toString());
int validate = validate(validityDate, nextDueDate);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(),Toast.LENGTH_SHORT).show();
}
Following is the code that finds the number of difference between two dates.
public static int validate(Date valid, Date nextDueDate) {
return (int) ((nextDueDate.getTime() - valid.getTime()) / (1000 * 60 * 60 * 24l));
}
The problem is that, im getting Date parser error at offset 3. Why is that so?
You need to use two different SimpleDateFormat
For date 23-May-2016 you need new SimpleDateFormat("dd-MMM-yyyy");
For date 24-May 2016 you need new SimpleDateFormat("dd-MMM yyyy");
You are using the pattern "dd-MM-yyyy" which means you're trying to parse a date of the form 12-05-2016.
If you need to parse a date such as "12-May-2016", then you have to use 3M letters for the month as follows. "dd-MMM-yyyy".
However, this will output "12-Jun-2016", if you parse the date "12-06-2016".
If you need the complete month, then you should use 4M letters. E.g: "dd-MMMM-yyyy". Then it will output 12-June-2016.

Android:Display time after adding GMT time zone

I am working on a App in which i want to display notification time.
I can display notification time but not able to add time zone in it.
My current location is Pakistan and i want to add GMT+5:00
My code is attached
String currentDateTimeString = DateFormat.getTimeInstance().format(notif.At);
textViewTime.setText(currentDateTimeString);
in this code, notif.At is dateTime variable. I also attached screenshot of my app, i want to ask you , how to add timeZone value in notif.At. Thanks!
Update
You mark time with timezone in order to solve internationalization problem, I understand, right?
If so, I think it could be better to convert your date to UTC date. When you change to another timezone, just convert this UTC Date to local.
public static Date localToUtc(Date localDate) {
return new Date(localDate.getTime()-TimeZone.getDefault().getOffset(localDate.getTime()));
}
public static Date utcToLocal(Date utcDate) {
return new Date(utcDate.getTime()+TimeZone.getDefault().getOffset(utcDate.getTime()));
}
Old answer
If your notif.At is Dateobject, it's a same question actually:
TimeZone tz = TimeZone.getDefault();
Date date = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String result = sdf.format(date);
Log.d("Date ", "date: " + result + " " + tz.getDisplayName(false, TimeZone.SHORT));
print:
date: 2015-03-31 18:45:28 GMT+08:00
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
LocalDateTime pst = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:00"));
LocalDateTime is = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:30"));

Android Timezone Ids are not matching with System Timezone Ids issue

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.

Categories

Resources