String format java dates

Format a Date to String in Java

Learn to format a given date to a specified formatted string in Java. We will learn to use inbuilt patterns and custom patterns with DateTimeFormatter and SimpleDateFormat.

1. Formatting with DateTimeFormatter [Java 8]

Since Java 8, We can use DateTimeFormatter for all types of date and time related formatting tasks. This class is thread-safe and immutable so can be used in concurrent environments without risks.

To format a date instance to string, we first need to create DateTimeFormatter instance with desired output pattern and then use its format() method to format the date.

1.1. Creating DateTimeFormatter

We can create DateTimeFormatter in three ways:

  1. Using inbuilt patterns
  2. Using custom patterns using ofPattern() method
  3. Using localized styles with FormatStyle , such as long or medium
//Use inbuilt pattern constants DateTimeFormatter inBuiltFormatter1 = DateTimeFormatter.ISO_DATE_TIME; DateTimeFormatter inBuiltFormatter2 = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //Define your own custom patterns DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma z"); //Using FormatStyle DateTimeFormatter customFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);

1.2. Formatting ZonedDateTime, LocalDateTime and LocalDate

The DateTimeFormatter class provides the methods String format(TemporalAccessor temporal) that can be used to format ZonedDateTime , LocalDateTime and LocalDate instances.

import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class FormattingDates < public static final String ZDT_PATTERN = "yyyy-MM-dd HH:mm:ss a z"; public static final DateTimeFormatter ZDT_FORMATTER = DateTimeFormatter.ofPattern(ZDT_PATTERN); public static final String LDT_PATTERN = "yyyy-MM-dd HH:mm:ss a"; public static final DateTimeFormatter LDT_FORMATTER = DateTimeFormatter.ofPattern(LDT_PATTERN); public static final String LD_PATTERN = "yyyy-MM-dd"; public static final DateTimeFormatter LD_FORMATTER = DateTimeFormatter.ofPattern(LD_PATTERN); public static void main(String[] args) < String instanceString = ZDT_FORMATTER.format(ZonedDateTime.now()); System.out.println(instanceString); String dateTimeString = LDT_FORMATTER.format(LocalDateTime.now()); System.out.println(dateTimeString); String dateString = LD_FORMATTER.format(LocalDate.now()); System.out.println(dateString); >> 

1.2. Creating Custom Patterns

Читайте также:  View class files in java

The custom pattern string can have any number of pre-defined letters and symbols which have their own meaning. The most used symbols are : Y, M, D, h, m, and s .

Also, note that the number of repetitions of a letter in the pattern also have different meanings. For example, “MMM” gives “Jan,” whereas “MMMM” gives “January.”

Let’s see these symbols for quick reference.

Symbol Meaning Type Example
G Era String AD; Anno Domini
y Year of era Year 2004 or 04
u Year of era Year Similar to ‘y’ but returns proleptic year.
D Day of year Number 235
M / L Month of year Number / String 7 or 07; J or Jul or July
d Day of month Number 21
Q / q Quarter of year Number / String 3 or 03; Q3 or 3rd quarter
Y Week based year Year 1996 or 96
w Week of week based year Number 32
W Week of month Number 3
e / c Localized day of week Number / String 2 or 02; T or Tue or Tuesday
E Day of week String T or Tue or Tuesday
F Week of month Number 3
a am / pm of the day String PM
h Clock hour of am pm (1-12) Number 12
K Hour of am pm (0-11) Number 0
k Clock hour of am pm (1-24) Number 15
H Hour of day (0-23) Number 15
m Minute of hour Number 30
s Second of minute Number 55
S Fraction of second Fraction 978
A Millisecond of day Number 1234
n Nanosecond of second Number 987654321
N Nanosecond of day Number 1234560000
V Time zone ID Zone-id America/Los_Angeles or Z or –08:30
z Time zone name Zone-name Pacific Standard Time or PST
X Zone offset Z for zero Offset-X Z or –08 or –0830 or –08:30 or –083015 or –08:30:15
x Zone offset Offset-x +0000 or –08 or –0830 or –08:30 or –083015 or –08:30:15
Z Zone offset Offset-Z +0000 or –0800 or –08:00
O Localized zone offset Offset-O GMT+8 or GMT+08:00 or UTC–08:00
p Pad next Pad modifier 1

If we try to use DateTimeFormatter with pattern that is not supported by the date-time instance, its format() will throw this exception.

For example, if we try to format LocalDate with pattern containing hours and minutes then this exception will be thrown, because LocalDate does not support any time information.

public static final String TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss a"; public static final DateTimeFormatter FOMATTER = DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN); String formmatedString = FOMATTER.format( LocalDate.now() );
 Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay at java.base/java.time.LocalDate.get0(LocalDate.java:709) at java.base/java.time.LocalDate.getLong(LocalDate.java:688) . 

2. Formatting with SimpleDateFormat [Java 7]

In case you are still stuck at Java 7 and can’t upgrade due to some legacy application’s dependencies, you can use SimpleDateFormat for date formatting in a locale-sensitive manner.

Though SimpleDateFormat is not thread-safe or immutable, still, it serves the purpose pretty well. Do not use this class in a multi-threaded environment without added synchronization.

2.1. Creating SimpleDateFormat

SimpleDateFormat provides the following constructors:

  • SimpleDateFormat(pattern) : uses the given pattern and the default date format symbols for the default locale.
  • SimpleDateFormat(pattern, locale) : uses the given pattern and the default date format symbols for the given locale.
  • SimpleDateFormat(pattern, formatSymbols) : uses the given pattern and date format symbols.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy"); SimpleDateFormat simpleDateFormat =new SimpleDateFormat("MM-dd-yyyy", new Locale("fr", "FR")); DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault()); symbols.setAmPmStrings(new String[] < "AM", "PM" >); //Override specific symbols and retaining others sdf.setDateFormatSymbols(symbols);

2.2. Convert Date to String

Now we can use the constructed SimpleDateFormat instance to format a given Date object to a string.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a"); String formattedDate = sdf.format(new Date()); System.out.println(formattedDate); String pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ"; SimpleDateFormat sdfWithLocale =new SimpleDateFormat(pattern, new Locale("fr", "FR")); String date = sdfWithLocale.format(new Date()); System.out.println(date); DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault()); symbols.setAmPmStrings(new String[] < "AM", "PM" >); sdf.setDateFormatSymbols(symbols); formattedDate = sdf.format(new Date()); System.out.println(formattedDate);
2022-02-17 21:57:01 pm jeudi février 2022 21:57:01.644+0530 2022-02-17 21:57:01 PM

If you have the liberty to upgrade a Java 7 application to the latest Java version, please do it on priority. The thread-safe and immutable nature of DateTimeFormatter is a huge win in terms of performance over SimpleDateFormat .

Both classes provide format() example which is used to format the date objects into a string.

Источник

Class SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. However, you are encouraged to create a date-time formatter with either getTimeInstance , getDateInstance , or getDateTimeInstance in DateFormat . Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the applyPattern methods as desired. For more information on using these methods, see DateFormat .

Date and Time Patterns

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from ‘A’ to ‘Z’ and from ‘a’ to ‘z’ are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes ( ‘ ) to avoid interpretation. «»» represents a single quote. All other characters are not interpreted; they’re simply copied into the output string during formatting or matched against the input string during parsing.

The following pattern letters are defined (all other characters from ‘A’ to ‘Z’ and from ‘a’ to ‘z’ are reserved):

Chart shows pattern letters, date/time component, presentation, and examples.
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996 ; 96
Y Week year Year 2009 ; 09
M Month in year (context sensitive) Month July ; Jul ; 07
L Month in year (standalone form) Month July ; Jul ; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday ; Tue
u Day number of week (1 = Monday, . 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time ; PST ; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08 ; -0800 ; -08:00
  • Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available. For parsing, both forms are accepted, independent of the number of pattern letters.
  • For formatting, if the number of pattern letters is 2, the year is truncated to 2 digits; otherwise it is interpreted as a number.
  • For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern «MM/dd/yyyy», «01/11/12» parses to Jan 11, 12 A.D.
  • For parsing with the abbreviated year pattern («y» or «yy»), SimpleDateFormat must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created. For example, using a pattern of «MM/dd/yy» and a SimpleDateFormat instance created on Jan 1, 1997, the string «01/11/12» would be interpreted as Jan 11, 2012 while the string «05/04/64» would be interpreted as May 4, 1964. During parsing, only strings consisting of exactly two digits, as defined by Character.isDigit(char) , will be parsed into the default century. Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn’t all digits (for example, «-1»), is interpreted literally. So «01/02/3» or «01/02/003» are parsed, using the same pattern, as Jan 2, 3 AD. Likewise, «01/02/-3» is parsed as Jan 2, 4 BC.

If week year ‘Y’ is specified and the calendar doesn’t support any week years, the calendar year ( ‘y’ ) is used instead. The support of week years can be tested with a call to getCalendar() . isWeekDateSupported() .

  • Letter M produces context-sensitive month names, such as the embedded form of names. Letter M is context-sensitive in the sense that when it is used in the standalone pattern, for example, «MMMM», it gives the standalone form of a month name and when it is used in the pattern containing other field(s), for example, «d MMMM», it gives the format form of a month name. For example, January in the Catalan language is «de gener» in the format form while it is «gener» in the standalone form. In this case, «MMMM» will produce «gener» and the month part of the «d MMMM» will produce «de gener». If a DateFormatSymbols has been set explicitly with constructor SimpleDateFormat(String,DateFormatSymbols) or method setDateFormatSymbols(DateFormatSymbols) , the month names given by the DateFormatSymbols are used.
  • Letter L produces the standalone form of month names.
GMTOffsetTimeZone: GMT Sign Hours : Minutes Sign: one of + - Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of 0 1 2 3 4 5 6 7 8 9

Hours must be between 0 and 23, and Minutes must be between 00 and 59. The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard. For parsing, RFC 822 time zones are also accepted.

RFC822TimeZone: Sign TwoDigitHours Minutes TwoDigitHours: Digit Digit
ISO8601TimeZone: OneLetterISO8601TimeZone TwoLetterISO8601TimeZone ThreeLetterISO8601TimeZone OneLetterISO8601TimeZone: Sign TwoDigitHours Z TwoLetterISO8601TimeZone: Sign TwoDigitHours Minutes Z ThreeLetterISO8601TimeZone: Sign TwoDigitHours : Minutes Z

Examples

The following examples show how date and time patterns are interpreted in the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time in the U.S. Pacific Time time zone.

Examples of date and time patterns interpreted in the U.S. locale
Date and Time Pattern Result
«yyyy.MM.dd G ‘at’ HH:mm:ss z» 2001.07.04 AD at 12:08:56 PDT
«EEE, MMM d, »yy» Wed, Jul 4, ’01
«h:mm a» 12:08 PM
«hh ‘o»clock’ a, zzzz» 12 o’clock PM, Pacific Daylight Time
«K:mm a, z» 0:08 PM, PDT
«yyyyy.MMMMM.dd GGG hh:mm aaa» 02001.July.04 AD 12:08 PM
«EEE, d MMM yyyy HH:mm:ss Z» Wed, 4 Jul 2001 12:08:56 -0700
«yyMMddHHmmssZ» 010704120856-0700
«yyyy-MM-dd’T’HH:mm:ss.SSSZ» 2001-07-04T12:08:56.235-0700
«yyyy-MM-dd’T’HH:mm:ss.SSSXXX» 2001-07-04T12:08:56.235-07:00
«YYYY-‘W’ww-u» 2001-W27-3

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Источник

Оцените статью