2

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!enter image description here

Umair Khalid
  • 2,259
  • 1
  • 21
  • 28
  • Duplicated with this Q&A [How to get TimeZone from android mobile?](http://stackoverflow.com/questions/7672597/how-to-get-timezone-from-android-mobile) – Weiyi Mar 31 '15 at 10:25

2 Answers2

3

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

Weiyi
  • 1,843
  • 2
  • 22
  • 34
  • its not working which i want, it is displaying time zone separately, i want to add time zone in my notification time. – Umair Khalid Mar 31 '15 at 11:03
1

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"));
Narendar Reddy M
  • 1,499
  • 1
  • 11
  • 18