簡體   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