如何将特定国家/地区的服务器时间转换为本地时间

时间:2017-08-19 05:39:36

标签: android

我正在尝试创建一个应用程序,我的应用程序将当地时间的信息发送到服务器,因为我的应用程序将在其他国家/地区使用,因此我希望显示与当地时间相关的信息发送时间。例如,如果我从孟加拉国时间向服务器发送当地时间aug 19,2017 11.37 am的信息,那么该信息将在南美洲显示时间aug 19,2017 0.36 am。我的服务器在美国/芝加哥。

我正在尝试使用以下代码但不能正常工作:

SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));

Date newDate= null;

try {
   newDate = simpleDateFormat.parse("2017-08-19 11:15:21");
   simpleDateFormat.setTimeZone(TimeZone.getDefault());

   String desireDate=simpleDateFormat.format(newDate);
   Log.v("TimeStamp",desireDate.toString());
} catch (ParseException e) {
   e.printStackTrace();
}

我在SO中看到了很多类似的问题,但没有人为我工作。

3 个答案:

答案 0 :(得分:0)

使用此代码,它为我工作..检查here的时区,不要忘记使用此代码 导入android.icu.text.SimpleDateFormat为> 24,< 24使用此import java.text.SimpleDateFormat;

DateFormat yourformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utc = TimeZone.getTimeZone("America/Chicago");
GregorianCalendar gc = new GregorianCalendar(utc);
Date now = gc.getTime();
Toast.makeText(this, yourformat.format(now) , Toast.LENGTH_SHORT).show();

答案 1 :(得分:0)

仅举例。

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
// you can get seconds by adding  "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); 

String localTime = date.format(currentLocalTime); 

答案 2 :(得分:0)

会检查来自您服务器的时间戳是否符合预期。如果来自服务器的时间戳没有转换为您期望的日期(在本地时区),那么时间戳和当前系统时间之间的差异将不是您所期望的。

使用日历获取当前时区。使用当前时区初始化SimpleDateFormatter;然后记录服务器时间戳并验证它是否是您期望的日期:

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

/* debug: is it local time? */
Log.d("Time zone: ", tz.getDisplayName());

/* date formatter in local timezone */
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);

/* print your timestamp and double check it's the date you expect */
long timestamp = cursor.getLong(columnIndex);
String localTime = sdf.format(new Date(timestamp * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds?
Log.d("Time: ", localTime);

如果打印的服务器时间不符合您的预期,那么您的服务器时间不是UTC。

如果打印的服务器时间是您期望的日期,那么您不必将rawoffset应用于它。所以你的代码会更简单(减去所有调试日志记录):

long timestamp = cursor.getLong(columnIndex);
Log.d("Server time: ", timestamp);

/* log the device timezone */
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone: ", tz.getDisplayName());

/* log the system time */
Log.d("System time: ", System.currentTimeMillis());

CharSequence relTime = DateUtils.getRelativeTimeSpanString(
    timestamp * 1000,
    System.currentTimeMillis(),
    DateUtils.MINUTE_IN_MILLIS);

((TextView) view).setText(relTime);
相关问题