簡體   English   中英

如何將 currentTimeMillis 轉換為 Java 中的日期?

[英]How to convert currentTimeMillis to a date in Java?

我在服務器中生成的某些日志文件中有毫秒,我也知道生成日志文件的語言環境,我的問題是將毫秒轉換為指定格式的日期。 該日志的處理發生在位於不同時區的服務器上。 轉換為“SimpleDateFormat”程序時會獲取機器的日期,因為這種格式化的日期不代表服務器的正確時間。 有沒有辦法優雅地處理這個?

long yourmilliseconds = 1322018752992l;
        //1322018752992-Nov 22, 2011 9:25:52 PM 

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS",Locale.US);

GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(yourmilliseconds);

System.out.println("GregorianCalendar -"+sdf.format(calendar.getTime()));

DateTime jodaTime = new DateTime(yourmilliseconds, 
                    DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss,SSS");

System.out.println("jodaTime "+parser1.print(jodaTime));

輸出:

Gregorian Calendar -2011-11-23 08:55:52,992
jodaTime 2011-11-22 21:25:52,992

您可以使用java.util.Date類,然后使用SimpleDateFormat來格式化Date

Date date=new Date(millis);

我們可以使用java.time包(教程)- Java SE 8 中引入的 DateTime API。

var instance = java.time.Instant.ofEpochMilli(millis);
var localDateTime = java.time.LocalDateTime
                        .ofInstant(instance, java.time.ZoneId.of("Asia/Kolkata"));
var zonedDateTime = java.time.ZonedDateTime
                            .ofInstant(instance,java.time.ZoneId.of("Asia/Kolkata"));

// Format the date

var formatter = java.time.format.DateTimeFormatter.ofPattern("u-M-d hh:mm:ss a O");
var string = zonedDateTime.format(formatter);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);

int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);

tl;博士

Instant.ofEpochMilli( 1_322_018_752_992L )     // Parse count of milliseconds-since-start-of-1970-UTC into an `Instant`.
       .atZone( ZoneId.of( "Africa/Tunis" ) )  // Assign a time zone to the `Instant` to produce a `ZonedDateTime` object.

細節

其他答案使用過時或不正確的類。

避免使用舊的日期時間類,例如 java.util.Date/.Calendar。 事實證明,它們設計不當、令人困惑且麻煩。

時間

java.time框架內置於 Java 8 及更高版本中。 大部分功能已向后移植到 Java 6 和 7,並進一步適用於 Android 由與制作Joda-Time相同的一些人制作。

一個InstantUTC時間線上的一個時刻,分辨率為納秒 它的紀元是 UTC 時間的 1970 年的第一個時刻。

假設您的輸入數據是從 1970-01-01T00:00:00Z 開始的毫秒計數(問題中不清楚),那么我們可以輕松實例化Instant

Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );

Instant.toString(): 2011-11-23T03:25:52.992Z

該標准ISO 8601格式字符串中的ZZulu縮寫,表示UTC

使用正確的時區名稱應用時區,以獲得ZonedDateTime

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );

查看此代碼在 IdeOne.com 上實時運行

Asia/Kolkata時區 ?

我猜您的代碼受到印度時區的影響。 我們在這里看到,調整到Asia/Kolkata時區會呈現與您報告的時間相同的時間,即08:55 ,比我們的 UTC 值03:25提前五個半小時。

2011-11-23T08:55:52.992+05:30[亞洲/加爾各答]

默認區域

您可以應用 JVM 的當前默認時區 請注意,默認值可能會在運行時隨時更改。 JVM 中任何應用程序的任何線程中的任何代碼都可以更改當前默認值。 如果重要,請詢問用戶他們想要/期望的時區。

ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

關於java.time

java.time框架內置於 Java 8 及更高版本中。 這些類取代麻煩的老傳統日期時間類,如java.util.DateCalendar ,和SimpleDateFormat

現在處於維護模式Joda-Time項目建議遷移到java.time類。

要了解更多信息,請參閱Oracle 教程 並在 Stack Overflow 上搜索許多示例和解釋。 規范是JSR 310

使用符合JDBC 4.2或更高版本的JDBC 驅動程序,您可以直接與您的數據庫交換java.time對象。 不需要字符串或 java.sql.* 類。

從哪里獲得 java.time 類?

ThreeTen-Extra項目用額外的類擴展了 java.time。 該項目是未來可能添加到 java.time 的試驗場。 您可以在這里找到一些有用的類,比如IntervalYearWeekYearQuarter ,和更多

最簡單的方法是使用Joda DateTime 類並指定以毫秒為單位的時間戳和所需的 DateTimeZone。

我強烈建議避免使用內置的 Java Date 和 Calendar 類; 他們太可怕了。

我的解決方案

public class CalendarUtils {

    public static String dateFormat = "dd-MM-yyyy hh:mm";
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);

    public static String ConvertMilliSecondsToFormattedDate(String milliSeconds){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(Long.parseLong(milliSeconds));
        return simpleDateFormat.format(calendar.getTime());
    }
}

如果毫秒值是自格林威治標准時間 1970 年 1 月 1 日以來的毫秒數,這是 JVM 的標准,那么這與時區無關。 如果要使用特定時區對其進行格式化,只需將其轉換為 GregorianCalendar 對象並設置時區即可。 之后,有多種方法可以對其進行格式化。

最簡單的方法:

private String millisToDate(long millis){

    return DateFormat.getDateInstance(DateFormat.SHORT).format(millis);
    //You can use DateFormat.LONG instead of SHORT

}

我這樣做:

static String formatDate(long dateInMillis) {
    Date date = new Date(dateInMillis);
    return DateFormat.getDateInstance().format(date);
}

您還可以使用帶有以下參數的getDateInstance(int style)

DateFormat.SHORT

DateFormat.MEDIUM

DateFormat.LONG

DateFormat.FULL

DateFormat.DEFAULT

SimpleDateFormat 類有一個名為 SetTimeZone(TimeZone) 的方法,它是從 DateFormat 類繼承的。 http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html

你可以試試 java.time api;

        Instant date = Instant.ofEpochMilli(1549362600000l);
        LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);

以下是我從毫秒到日期格式獲取日期的解決方案。 您必須使用Joda 庫來運行此代碼。

import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class time {

    public static void main(String args[]){

        String str = "1431601084000";
        long geTime= Long.parseLong(str);
        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
        calendar.setTimeInMillis(geTime);
        DateTime jodaTime = new DateTime(geTime, 
               DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
        DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd");
        System.out.println("Get Time : "+parser1.print(jodaTime));

   }
}
public static LocalDateTime timestampToLocalDateTime(Long timestamp) {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone.getDefault().toZoneId());
}
 public static String getFormatTimeWithTZ(Date currentTime) {
    SimpleDateFormat timeZoneDate = new SimpleDateFormat("EEE, dd-MM-yyyy  hh:mm a", Locale.getDefault());
    return timeZoneDate.format(currentTime);
}

輸出是

Mon,01-03-2021 07:37 PM

public static String getFormatTimeWithTZ(Date currentTime) {
    SimpleDateFormat timeZoneDate = new SimpleDateFormat("EEE, dd-MM-yyyy  HH:mm ", Locale.getDefault());
    return timeZoneDate.format(currentTime);
}

輸出是

Mon,01-03-2021 19:37

如果您不想要 Days Then Remove EEE,
如果您不想要日期,則刪除 dd-MM-yyyy
如果您想要以小時、分鍾、秒、毫秒為單位的時間,請使用 HH:mm:ss.SSS

並在您想要的地方調用此方法

getFormatTimeWithTZ(Mydate)

在哪里

Date Mydate = new Date(System.currentTimeMillis());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM