您好我有一个使用webRequest
返回时间戳类型为Int(或Long)的Android应用程序我想将其转换为人类阅读器日期时间(根据设备时区)
例如1175714200转换为GMT:周三,2007年4月4日19:16:40 GMT 您的时区:2007年4月5日,格林威治标准时间上午3:16:40 + 8:00
我已经使用此功能转换但似乎没有返回正确的结果(所有结果都像(15/01/1970 04:04:25)这是不正确的
time.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
format(new Date(topStory.getTime() * 1000)));
上述代码有什么问题吗?
我也有警告信息:
要获取本地格式,请使用getDateInstance(),getDateTimeInstance()或getTimeInstance(),或使用新的SimpleDateFormat(String模板,Locale语言环境),例如Locale.US用于ASCII日期。少...(Ctrl + F1) 几乎所有调用者都应该使用getDateInstance(),getDateTimeInstance()或getTimeInstance()来获取适合用户语言环境的现成SimpleDateFormat实例。你直接创建这个类的一个实例的主要原因是你需要格式化/解析一个特定的机器可读格式,在这种情况下你几乎肯定要明确要求美国确保你得到ASCII数字(而不是,比方说,阿拉伯数字)。
答案 0 :(得分:3)
尝试此功能:
private String formatDate(long milliseconds) /* This is your topStory.getTime()*1000 */ {
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliseconds);
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
return sdf.format(calendar.getTime());
}
它从正在使用的设备获取默认时区。如果您有任何疑问/疑问,请发表评论。此外,此函数将自上一纪元以来的毫秒数作为输入。如果那不是你的topStory.getTime()返回的内容,那么这个函数将不起作用。在这种情况下,您需要将topStory.getTime()的返回值转换为自上一纪元以来的毫秒数。
答案 1 :(得分:1)
我一直使用这个SimpleDateFormat,所以这是我使用的代码
public static String dateToString(Date date, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
我只是从我的上下文中调用它,如
dateToString(new Date(), "dd_MM_yyyy_HH_mm");
小心使用斜杠/或\ ...通常会使用其他含义来破坏您的格式。 new Date()
为您提供当前时间的新实例,因此无需在format()
取自日期| Android开发者网站
Date()将此Date实例初始化为当前时间。
日期(长毫秒) 使用指定的毫秒值初始化此Date实例。
编辑:如果不需要当前时间使用GregorianCalendar对象!
GregorianCalendar(int year,int month,int day) 在指定日期在默认的TimeZone和Locale中构造一个初始化为午夜的新GregorianCalendar。
然后使用
GregorianCalendar cal = new GregorianCalendar(2001,11,25);
cal.add(GregorianCalendar.MONTH,2);
cal.get(GregorianCalendar.YEAR); //Returns 2002
cal.get(GregorianCalendar.MONTH); //Returns 1
cal.get(GregorianCalendar.DATE); //Returns 25
答案 2 :(得分:1)
如果topStory.getTime()
返回一个int(而不是long),则乘以1000可能会溢出int数范围。
为了解决这个问题,使用长数来计算乘法:
topStory.getTime() * 1000L
答案 3 :(得分:0)
此代码中的topStory
是日历实例吗?
乘以1000的目的是什么?
尝试将其替换为Calendar.getInstance()
并删除* 1000
以进行调试并检查输出。
如果是当前时间,那么格式化不是故障,而是您的输入。
警告很可能只是因为您的输入不是某个建议类的实例(如Calendar
)。
答案 4 :(得分:0)
long DateInLong = 1584212400;
Date date = new Date(DateInLong * 1000L);
SimpleDateFormat simpledateformate = new SimpleDateFormat("yyyy-MM-dd");
String DATE = simpledateformate.format(date);