繁体   English   中英

Android:将秒转换为年,日,小时,分钟,秒

[英]Android : Convert seconds to year, day, hours, minutes, seconds

我正在使用已编码的JSON文件进行Android项目。

所以我有这个:

{
  "type": "Feature",
  "properties": {
    "mag": 1.29,
    "place": "10km SSW of Idyllwild, CA",
    "time": 1388620296020,
    "updated": 1457728844428
  }
}

我想将time转换为年,日,小时和秒。 我知道有很多话题谈论我的问题,但是我已经尝试过了,但没有成功。

Android中 ,您可以使用ThreeTen Backport (这是Java 8的新日期/时间类的绝佳反向端口) ,以及ThreeTenABP (有关如何在此处使用的更多信息 )。

该API提供了一种处理日期的好方法,比过时的DateCalendar更好(旧类( DateCalendarSimpleDateFormat )存在很多问题 ,它们将被新的API取代)。

要从时间戳记值获取日期(假设1388620296020是距unix纪元的毫秒数),可以使用org.threeten.bp.Instant类:

// create the UTC instant from 1388620296020
Instant instant = Instant.ofEpochMilli(1388620296020L);
System.out.println(instant); // 2014-01-01T23:51:36.020Z

输出为2014-01-01T23:51:36.020Z ,因为Instant始终使用UTC。 如果要将其转换为另一个时区中的日期/时间,则可以使用org.threeten.bp.ZoneId类并创建org.threeten.bp.ZonedDateTime

ZonedDateTime z = instant.atZone(ZoneId.of("Europe/Paris"));
System.out.println(z); // 2014-01-02T00:51:36.020+01:00[Europe/Paris]

输出将为2014-01-02T00:51:36.020+01:00[Europe/Paris] (同一UTC即时转换为巴黎时区)。

请注意,API避免使用3个字母的时区名称(例如ECTCST ),因为它们是模棱两可的,不是标准的 始终喜欢使用全名(例如,由IANA数据库定义的Europe/ParisAmerica/Los_Angeles )-您可以通过调用ZoneId.getAvailableZoneIds()获得所有可用的名称。

如果要以其他格式打印日期,则可以使用org.threeten.bp.format.DateTimeFormatter (请参阅javadoc以查看所有可能的格式):

ZonedDateTime z = instant.atZone(ZoneId.of("Europe/Paris"));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SSS Z");
System.out.println(fmt.format(z)); // 02/01/2014 00:51:36.020 +0100

您有整数溢出。 只需使用以下命令(在1000常数后注意“ L”):

 Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000L);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......

看到这个: https : //stackoverflow.com/a/5246444/7161543

可以是这样;

long jsondate = 1388620296020L;
Date dt = new Date (jsondate); 
SimpleDateFormat sd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(sd.format(dt));

尝试这个

long uptime = 1388620296020;

long days = TimeUnit.MILLISECONDS
.toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);

long hours = TimeUnit.MILLISECONDS
.toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);

long minutes = TimeUnit.MILLISECONDS
.toMinutes(uptime);
 uptime -= TimeUnit.MINUTES.toMillis(minutes);

long seconds = TimeUnit.MILLISECONDS
.toSeconds(uptime);

这是较短的:

    long lg=1388620296020l;
    Date date = new Date(lg);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM