简体   繁体   English

如何将 currentTimeMillis 转换为 Java 中的日期?

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

I have milliseconds in certain log file generated in server, I also know the locale from where the log file was generated, my problem is to convert milliseconds to date in specified format.我在服务器中生成的某些日志文件中有毫秒,我也知道生成日志文件的语言环境,我的问题是将毫秒转换为指定格式的日期。 The processing of that log is happening on server located in different time zone.该日志的处理发生在位于不同时区的服务器上。 While converting to "SimpleDateFormat" program is taking date of the machine as such formatted date do not represent correct time of the server.转换为“SimpleDateFormat”程序时会获取机器的日期,因为这种格式化的日期不代表服务器的正确时间。 Is there any way to handle this elegantly ?有没有办法优雅地处理这个?

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));

Output:输出:

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

You may use java.util.Date class and then use SimpleDateFormat to format the Date .您可以使用java.util.Date类,然后使用SimpleDateFormat来格式化Date

Date date=new Date(millis);

We can use java.time package (tutorial) - DateTime APIs introduced in the Java SE 8.我们可以使用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;dr 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.

Details细节

The other answers use outmoded or incorrect classes.其他答案使用过时或不正确的类。

Avoid the old date-time classes such as java.util.Date/.Calendar.避免使用旧的日期时间类,例如 java.util.Date/.Calendar。 They have proven to be poorly designed, confusing, and troublesome.事实证明,它们设计不当、令人困惑且麻烦。

java.time时间

The java.time framework comes built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 Much of the functionality is backported to Java 6 & 7 and further adapted to Android .大部分功能已向后移植到 Java 6 和 7,并进一步适用于 Android Made by the some of the same folks as had made Joda-Time .由与制作Joda-Time相同的一些人制作。

An Instant is a moment on the timeline in UTC with a resolution of nanoseconds .一个InstantUTC时间线上的一个时刻,分辨率为纳秒 Its epoch is first moment of 1970 in UTC.它的纪元是 UTC 时间的 1970 年的第一个时刻。

Assuming your input data is a count of milliseconds from 1970-01-01T00:00:00Z (not clear in the Question), then we can easily instantiate an Instant .假设您的输入数据是从 1970-01-01T00:00:00Z 开始的毫秒计数(问题中不清楚),那么我们可以轻松实例化Instant

Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );

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

The Z in that standard ISO 8601 formatted string is short for Zulu and means UTC .该标准ISO 8601格式字符串中的ZZulu缩写,表示UTC

Apply a time zone using a proper time zone name , to get a ZonedDateTime .使用正确的时区名称应用时区,以获得ZonedDateTime

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

See this code run live at IdeOne.com .查看此代码在 IdeOne.com 上实时运行

Asia/Kolkata time zone ? Asia/Kolkata时区 ?

I am guessing your are had an India time zone affecting your code.我猜您的代码受到印度时区的影响。 We see here that adjusting into Asia/Kolkata time zone renders the same time-of-day as you report, 08:55 which is five and a half hours ahead of our UTC value 03:25 .我们在这里看到,调整到Asia/Kolkata时区会呈现与您报告的时间相同的时间,即08:55 ,比我们的 UTC 值03:25提前五个半小时。

2011-11-23T08:55:52.992+05:30[Asia/Kolkata] 2011-11-23T08:55:52.992+05:30[亚洲/加尔各答]

Default zone默认区域

You can apply the current default time zone of the JVM.您可以应用 JVM 的当前默认时区 Beware that the default can change at any moment during runtime .请注意,默认值可能会在运行时随时更改。 Any code in any thread of any app within the JVM can change the current default. JVM 中任何应用程序的任何线程中的任何代码都可以更改当前默认值。 If important, ask the user for their desired/expected time zone.如果重要,请询问用户他们想要/期望的时区。

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

About java.time关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database.使用符合JDBC 4.2或更高版本的JDBC 驱动程序,您可以直接与您的数据库交换java.time对象。 No need for strings or java.sql.* classes.不需要字符串或 java.sql.* 类。

Where to obtain the java.time classes?从哪里获得 java.time 类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目用额外的类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.最简单的方法是使用Joda DateTime 类并指定以毫秒为单位的时间戳和所需的 DateTimeZone。

I strongly recommend avoiding the built-in Java Date and Calendar classes;我强烈建议避免使用内置的 Java Date 和 Calendar 类; they're terrible.他们太可怕了。

My Solution我的解决方案

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());
    }
}

If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone.如果毫秒值是自格林威治标准时间 1970 年 1 月 1 日以来的毫秒数,这是 JVM 的标准,那么这与时区无关。 If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone.如果要使用特定时区对其进行格式化,只需将其转换为 GregorianCalendar 对象并设置时区即可。 After that there are numerous ways to format it.之后,有多种方法可以对其进行格式化。

Easiest way:最简单的方法:

private String millisToDate(long millis){

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

}

I do it like this:我这样做:

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

You can also use getDateInstance(int style) with following parameters:您还可以使用带有以下参数的getDateInstance(int style)

DateFormat.SHORT

DateFormat.MEDIUM

DateFormat.LONG

DateFormat.FULL

DateFormat.DEFAULT

The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. SimpleDateFormat 类有一个名为 SetTimeZone(TimeZone) 的方法,它是从 DateFormat 类继承的。 http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html

You can try java.time api;你可以试试 java.time api;

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

Below is my solution to get date from miliseconds to date format.以下是我从毫秒到日期格式获取日期的解决方案。 You have to use Joda Library to get this code run.您必须使用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);
}

Output is输出是

Mon,01-03-2021 07:37 PM

and

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

output is输出是

Mon,01-03-2021 19:37

if you do not want the Days Then Remove EEE,如果您不想要 Days Then Remove EEE,
if you do not want the Date Then Remove dd-MM-yyyy如果您不想要日期,则删除 dd-MM-yyyy
If you want Time in Hour, Minutes, Second, Millisecond then Use HH:mm:ss.SSS如果您想要以小时、分钟、秒、毫秒为单位的时间,请使用 HH:mm:ss.SSS

and Call this method where you want并在您想要的地方调用此方法

getFormatTimeWithTZ(Mydate)

where在哪里

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

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

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