Java에서 YYYY-MM-DD HH : MI : Sec.Millisecond 형식으로 현재 시간을 얻는 방법은 무엇입니까?
아래 코드는 현재 시간을 알려줍니다. 그러나 밀리 초에 대해서는 아무것도 알려주지 않습니다.
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
2009-09-22 16:47:08 (YYYY-MM-DD HH : MI : Sec) 형식으로 날짜를 얻습니다 .
하지만 현재 시간을 2009-09-22 16:47:08.128((YYYY-MM-DD HH : MI : Sec.Ms) 형식으로 검색하고 싶습니다 . 여기서 128은 밀리 초를 나타냅니다.
SimpleTextFormat잘 작동합니다. 여기서 가장 낮은 시간 단위는 초이지만 밀리 초도 어떻게 얻습니까?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
자바 원 라이너
public String getCurrentTimeStamp() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
JDK8 스타일
public String getCurrentLocalDateTimeStamp() {
return LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}
날짜 형식 문자열에 밀리 초 필드 만 추가하면됩니다.
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat 의 API 문서 는 형식 문자열에 대해 자세히 설명합니다.
이 시도:-
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));
또는
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
tl; dr
Instant.now()
.toString()
2016-05-06T23 : 24 : 25.694Z
ZonedDateTime.now(
ZoneId.of( "America/Montreal" )
).format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
2016-05-06 19 : 24 : 25.694
java.time
In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.
If you want to eliminate any microseconds or nanoseconds from your data, truncate.
Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;
The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.
An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.
Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();
2016-05-06T23:24:25.694Z
Replace the T in the middle with a space, and the Z with nothing, to get your desired output.
String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.
2016-05-06 23:24:25.694
As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.
String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );
Joda-Time
The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.
The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.
System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
When run…
Now: 2013-11-26T20:25:12.014Z
Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:
int millisOfSecond = myDateTime.getMillisOfSecond ();
The easiest way was to (prior to Java 8) use,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But SimpleDateFormat is not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Time document has a good overview about it.
So in Java 8 something like below will do the trick (to format the current date/time),
LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
And one thing to note is it was developed with the help of the popular third party library joda-time,
The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.
But now the joda-time is becoming deprecated and asked the users to migrate to new java.time.
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project
Anyway having said that,
If you have a Calendar instance you can use below to convert it to the new java.time,
Calendar calendar = Calendar.getInstance();
long longValue = calendar.getTimeInMillis();
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(date.toString()); // 2018-03-06T15:56:53.634
System.out.println(formattedString); // 2018-03-06 15:56:53.634
If you had a Date object,
Date date = new Date();
long longValue2 = date.getTime();
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
System.out.println(formattedString); // 2018-03-06 15:59:30.278
If you just had the epoch milliseconds,
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());
I would use something like this:
String.format("%tF %<tT.%<tL", dateTime);
Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.
To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.
import java.text.SimpleDateFormat;
import java.util.Date;
public class test {
public static void main(String argv[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println(strDate);
}
}
Use this to get your current time in specified format :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.print(dateFormat.format(System.currentTimeMillis())); }
I don't see a reference to this:
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
above format is also useful.
The doc in Java 8 names it fraction-of-second , while in Java 6 was named millisecond. This brought me to confusion
You can simply get it in the format you want.
String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));
'Programing' 카테고리의 다른 글
| 힘내에서 풀이 필요한지 확인 (0) | 2020.10.03 |
|---|---|
| MySQL에서 새 사용자를 만들고 하나의 데이터베이스에 대한 전체 액세스 권한을 부여합니다. (0) | 2020.10.03 |
| 확인없이 cp를 강제로 덮어 쓰는 방법 (0) | 2020.10.03 |
| 상위 페이지의 iframe에서 JavaScript 코드 호출 (0) | 2020.10.03 |
| Akka의 좋은 사용 사례 [종료 됨] (0) | 2020.10.03 |