publicstaticvoidmain(String[] args)throws Exception{ Calendarcal= Calendar.getInstance(); SimpleDateFormatsdf=newSimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS"); StringstrDate= sdf.format(cal.getTime()); System.out.println("Current date in String Format: "+strDate);
SimpleDateFormatsdf1=newSimpleDateFormat(); sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS"); Datedate= sdf1.parse(strDate); System.out.println("Current date in Date Format: "+date); } }
И я получаю следующий вывод
Current date in String Format: 05/01/201221:10:17.287 Current date in Date Format: Thu Jan 0521:10:17 IST 2012
Пожалуйста, подскажите, что мне следует сделать, чтобы отобразить дату в том же строковом формате (dd / MM / yyyy HH: mm: ss.SS), т. е. я хочу следующий вывод:
Current date in String Format: 05/01/201221:10:17.287 Current date in Date Format: 05/01/201221:10:17.287
Вы не можете - потому что вы вызываете, Date.toString() который всегда будет включать системный часовой пояс, если это формат даты по умолчанию для языка по умолчанию. Само по себе значение Date не имеет понятия о формате. Если вы хотите отформатировать его определенным образом, используйте SimpleDateFormat.format()... использование Date.toString() почти всегда плохая идея.
Ответ 3
Следующий код выдает ожидаемый результат. Это то, что вы хотите?
import java.util.Calendar; import java.util.Date;
publicclassDateAndTime {
publicstaticvoidmain(String[] args)throws Exception { Calendarcal= Calendar.getInstance(); SimpleDateFormatsdf=newSimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS"); StringstrDate= sdf.format(cal.getTime()); System.out.println("Current date in String Format: " + strDate);
SimpleDateFormatsdf1=newSimpleDateFormat(); sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS"); Datedate= sdf1.parse(strDate); Stringstring= sdf1.format(date); System.out.println("Current date in Date Format: " + string);
} }
Ответ 4
tl;dr
Use modern java.time classes.
Never use Date/Calendar/SimpleDateFormat classes.
Example:
ZonedDateTime // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone). .now( // Capture the current moment. ZoneId.of( "Africa/Tunis" ) // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc. ) .truncatedTo( // Lop off finer part of this value. ChronoUnit.MILLIS // Specify level of truncation via `ChronoUnit` enum object. ) // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original. .format( // Generate a `String` object with text representing the value of our `ZonedDateTime` object. DateTimeFormatter.ISO_LOCAL_DATE_TIME // This standard ISO 8601 format is close to your desired output. ) // Returns a `String`. .replace( "T" , " " ) // Replace `T` in middle with a SPACE.
java.time
The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.
want current date and time
Capture the current moment in UTC using Instant.
Instantinstant= Instant.now() ;
To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneIdz= ZoneId.of( "Pacific/Auckland" ) ; ZonedDateTimezdt= instant.atZone( z ) ;
Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.
The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.
I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.
But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.
Never exchange date-time values using text intended for presentation to humans.
Instead, use the standard formats defined for this very purpose, found in ISO 8601.
The java.time use these ISO 8601 formats by default when parsing/generating strings.
Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
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.