在下面的代码中,当我静态地将本地时区设置为asia/kolkatta
等时,时区会发生变化。但当我动态地设置时,时区不会发生变化。当用户更改时区时,我检查了本地时区中的值。它更改正确,并将值保持为asia/kolkatta
。
public String cinverttoutc(String time) {
String currenttimeformat = "";
String twelvehourformat = "";
try {
Calendar calendar = new GregorianCalendar();
TimeZone timeZone = calendar.getTimeZone();
String Timezonename = timeZone.getID();
TimeZone tz = TimeZone.getTimeZone(Timezonename);
localtimezone = tz.getID();
Log.i("localtimezone",localtimezone);
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = new Date();
String dateis = sdf.format(dt);
String dateandtime = dateis + " " + time;
final SimpleDateFormat sdf1 = new SimpleDateFormat(DATEFORMAT);
SimpleDateFormat twelv`enter code here`ehour = new SimpleDateFormat("hh:mm aa");
TimeZone utcZone = TimeZone.getTimeZone(localtimezone);
sdf1.setTimeZone(utcZone);
Date myDate = sdf1.parse(dateandtime);
sdf1.setTimeZone(TimeZone.getDefault());
String Currentformat = sdf1.format(myDate);
DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat timeFormat = new SimpleDateFormat("hh:mm aa");
Date now = readFormat.parse(Currentformat);
currenttimeformat = timeFormat.format(now);
} catch (ParseException e) {
}
return currenttimeformat;
}
您可以使用此方法为所有获取本地时区
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone","="+tz.getDisplayName());
localtimezone = tz.getID();
Log.i("localtimezone",localtimezone);
在这里你可以更改的格式
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
sdf.setTimeZone(TimeZone.getTimeZone(localtimezone));