currentTimeMillis를 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
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);
java.util.Date
클래스를 사용한 다음 SimpleDateFormat
형식 을 지정하는 데 사용할 수 있습니다 Date
.
Date date=new Date(millis);
Java SE 8에 도입 된 java.time 패키지 (자습서)-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);
tl; dr
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.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 대부분의 기능은 Java 6 & 7로 백 포트 되어 Android에 더욱 적합합니다 . Joda-Time을 만든 것과 같은 사람들 중 일부가 만들었습니다 .
가 Instant
있는 타임 라인에 순간 UTC 의 해상도를 가진 나노초 . 그 시대 는 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
The Z
in that standard ISO 8601 formatted string is short for Zulu
and means UTC.
Apply a time zone using a proper time zone name, to get a ZonedDateTime
.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );
See this code run live at IdeOne.com.
Asia/Kolkata
time zone ?
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
.
2011-11-23T08:55:52.992+05:30[Asia/Kolkata]
Default zone
You can apply the current default time zone of the 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. If important, ask the user for their desired/expected time zone.
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
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. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.
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.
I strongly recommend avoiding the built-in Java Date and Calendar classes; 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());
}
}
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:
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. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Easiest way:
private String millisToDate(long millis){
return DateFormat.getDateInstance(DateFormat.SHORT).format(millis);
//You can use DateFormat.LONG instead of SHORT
}
Below is my solution to get date from miliseconds to date format. You have to use Joda Library to get this code run.
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));
}
}
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
참고URL : https://stackoverflow.com/questions/8237193/how-to-convert-currenttimemillis-to-a-date-in-java
'IT' 카테고리의 다른 글
Windows에서 명령 프롬프트를 사용하여 8080이 아닌 다른 포트에서 jenkins를 시작하는 방법은 무엇입니까? (0) | 2020.07.03 |
---|---|
'AndroidJUnit4'기호를 확인할 수 없습니다 (0) | 2020.07.03 |
reStructuredText 도구 지원 (0) | 2020.07.03 |
설치된 모든 node.js 모듈 목록을 인쇄하십시오. (0) | 2020.07.03 |
String 객체를 Hash 객체로 어떻게 변환합니까? (0) | 2020.07.03 |