我想将带有时区的json时间戳转换为在Android设备上显示的字符串。
Json时间戳是:/Date(1379488920000+0200)/
输出应考虑Android设备所在的时区和设备上配置的格式(AM / PM或24小时)。输出应仅显示小时和分钟。
此代码有效,但它没有处理时区,设备时区和设备格式:
String timestamp = jsonDate.split("\\(")[1].split("\\+")[0];
String departure = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT)
.format(new Date(Long.parseLong(timestamp)));
答案 0 :(得分:0)
我最终在构造函数中设置了上下文,并从重写的run函数传递它。
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new FetchData(context, appWidgetManager), 1, 30000);
}
private class FetchData extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
Context thisContext = null;
public FetchData(Context context, AppWidgetManager appWidgetManager)
{
thisContext = context;
this.appWidgetManager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
thisWidget = new ComponentName(context, HelloWidget.class);
}
@Override
public void run()
{
String restUrl = TrainFromSki;
remoteViews.setTextViewText(R.id.widget_textview, GetTextData(thisContext, restUrl));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
在GetTextData内部,我按照设备设置格式化日期:
String jsonDate = "/ Date(1379488920000+0200) /";
String timestamp = jsonDate.split("\\(")[1].split("\\+")[0];
String departure = DateFormat.getTimeFormat(context)
.format(new Date(Long.parseLong(timestamp)));