【问题标题】:Android:Display the device time using joda in chatAndroid:在聊天中使用joda显示设备时间
【发布时间】:2014-01-09 04:35:24
【问题描述】:
我需要在聊天中显示设备时间,但它只显示区域时间。如果我更改设备时间,两个时间将不一样。
我想在我使用 joda 的时间戳中显示当前设备时间。请检查我的代码。
DateTime createdAt = message.getCreatedAt();
DateTimeZone dateTimeZone= DateTimeZone.getDefault();
DateTimeFormatter fmtTimeBubble = DateTimeFormat.forPattern(LBUtil.TIME_AM_PM_FORMAT).withZone(dateTimeZone);
viewHolder.dateTime.setText(fmtTimeBubble.print(createdAt));
【问题讨论】:
标签:
android
timestamp
chat
jodatime
【解决方案1】:
使用以下方法根据任何时区获取时间,您必须传递 3 个参数:
- 系统当前时间,以毫秒为单位。
- 设备时区
-
而且,时间格式如 (MMM dd, hh:mm a)
public static String getFormatedTime(long dateTime,String timeZone, String format){
String time = null;
try{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(dateTime);
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
time = sdf.format(cal.getTime());
}
catch(Exception e){
//logger.log(Level.SEVERE,"\n ERROR**********, Exception during get formated time: "+e+"\n");
}
return time;
}
要调用此方法,您必须以编程方式获取设备时区:
Calendar calendar = Calendar.getInstance();
TimeZone zone = calendar.getTimeZone();
String timeZone = zone.getID();
现在调用这个方法:
String msgAtTime = getFormattedTime(System.currentTimeInMillis(), timezone, "MMM dd, hh:mm a");
现在,在textview 中设置返回字符串。
msgTextVies.setText(msgAtTime);