Progress28.ru

IT Новости


09ae9cb0
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java text simpledateformat

Java SimpleDateFormat Example

Posted by: Konstantina Dimtsa in text July 3rd, 2014 0 Views

In this example we will show how to use the Java SimpleDateFormat class – java.text.SimpleDateFormat , so as to convert a Date into a formatted string or a string to a Date .

You can make this conversion using the constructors provided by java.text.SimpleDateFormat class and some patterns, such as dd/MM/yyyy , dd-MM-yy and so on, so as to format the Date as you wish. We will show more examples of patterns and format symbols in the following sections.

1. Java SimpleDateFormat – Constructors

There are four constructors that you can use so as to create a java.text.SimpleDateFormat .

  • SimpleDateFormat()
    The simplest constructor which creates a java.text.SimpleDateFormat with a default pattern of date and a default locale.
  • SimpleDateFormat(String pattern)
    The constructor which creates a java.text.SimpleDateFormat with a given pattern and a default locale.
  • SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
    Constructs a java.text.SimpleDateFormat with the given pattern and specific date format symbols. DateFormatSymbols is a class for encapsulating localizable date-time formatting data, such as the names of the months, the names of the days of the week, and the time zone data.
  • SimpleDateFormat(String pattern, Locale locale)
    Constructs a java.text.SimpleDateFormat with the given pattern and a specific locale.

2. Pattern Syntax

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear1996 ; 96
YWeek yearYear2009 ; 09
MMonth in year (context sensitive)MonthJuly ; Jul ; 07
LMonth in year (standalone form)MonthJuly ; Jul ; 07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesday ; Tue
uDay number of week (1 = Monday, …, 7 = Sunday)Number1
aAm/pm markerTextPM
HHour in day (0-23)Number
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time ; PST ; GMT-08:00
ZTime zoneRFC 822 time zone-0800
XTime zoneISO 8601 time zone-08 ; -0800 ; -08:00

3. Pattern Examples

Date and Time PatternResult
«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

4. Example of SimpleDateFormat

Create a java class named SimpleDateFormatExample.java with the following code:

Let’s explain the different formats of SimpleDateFormat class in the above code. Firstly, we create a Date object which is initialized with the current date and time. Then, we create different date formatters with different patterns, such as:

  • The default pattern, which shows the date in the form of month/day/year and the time using the 12-hour clock.
  • yyyy/MM/dd , which shows the date in the form of year/month/day. As we can observe, the pattern for the year has 4 letters, which means that the full form of the year will be used (e.g. 2014). Otherwise a short or abbreviated form is used if available.
  • dd-M-yyyy hh:mm:ss , which shows the date in the form of date-month-year (the month will be shown in the abbreviated form, as it has only one letter and not two as in the previous case) and futhermore, it shows the time (hour, minutes and seconds) while the hour is in am/pm format.
  • dd MMMM yyyy zzzz , which shows the date and the timezone in full format. We can observe that we also defined the locale of the date/time: Locale.ENGLISH or Locale.ITALIAN below.
  • E, dd MMM yyyy HH:mm:ss z , which shows the date, the day name of the week and the time (we can see that the hour is in capital, which means that the hour’s values here are between 0 – 23, as we use the 24-hour clock).
  • EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ , which shows the day name, date, name of the month, year, 24H clock with seconds and 3 digits of milliseconds and timezone.

You may notice that there is a slight but basic difference to the followings:

  • mm: representes the minutes.
  • MM: represents the Month.
  • dd: represents the day.
  • DD: represents the day in year (e.g. 189 out of 365).
  • hh: represents the hour’s value using the 12-hour clock.
  • HH: represents the hour’s value using the 24-hour clock.

Using all those formatters, we format dates as strings.

Finally, we show a reverse example, where we parse a string into date, using the parse() method.

If we run the above code, we will have the following results:

Java text simpledateformat

DateFormat and SimpleDateFormat Examples

Version 1.1 of Java introduced the java.text package, which included utility classes for parsing and formatting numbers and dates, along with utility classes for building other kinds of parsers.

Default date formats
The java.text.DateFormat class, and its concrete subclass java.text.SimpleDateFormat , provide a convenient way to convert strings with date and/or time info to and from java.util.Date objects. Figure 1 shows an example of using default DateFormat objects to format a date in a variety of ways:

Figure 1. Using default DateFormat objects to format a Date object.

When you run this class, you will see output that looks something like that shown in Figure 2.

Figure 2. Output from example in Figure 1

Default DateFormat objects retrieved from the static getInstance() , getTimeInstance() , and getDateTimeInstance() methods can also be used for parsing String objects to produce Date objects. Figure 3 shows a simple example of this.

Figure 3. Using default DateFormat objects to parse a String

The result is shown in Figure 4. Note that since the string version of the date did not contain timezone or seconds, the timezone is set to the default timezone (EST, in this case) and the seconds are set to zero.

Figure 4. Parsing a date string

The parse method throws an exception if a date matching the format cannot be parsed. In the code shown in Figure 3, the string matches the format exactly. To see what happens when a bad string is encountered, the class in Figure 5 reads and attempts to parse input until a blank line (or a Control-D) is entered.

Figure 5. Example of parsing dates entered on the command line

Figure 6 shows an example of running this class and entering several date strings. (Text entered is shown in italics.)

Figure 6. Parsing a variety of date strings

Note that the default parser is somewhat flexible. It recognizes a long version of the month name (“November” instead of “Nov”), but does not recognize the two dates shown in red, both of which are missing AM or PM. Furthermore, it produces possibly unexpected results when the time “20:14 PM” is entered: The parsed date is 8:14 the next morning.

DateFormat actually gives you a small amount of control over leniency in parsing. The default DateFormat instances are lenient by default, but invoking format.setLenient(false); in the example in Figure 5 would cause the “20:14 PM” example (in Figure 6) to fail, though it will still accept “November” or “Nov”.

Using SimpleDateFormat for custom date formatting and parsing

The default DateFormat instances returned by the static methods in the DateFormat class may be sufficient for many purposes, but clearly do not cover all possible valid or useful formats for dates. For example, notice that in Figure 2, none of the DateFormat -generated strings (numbers 2 – 9) match the format of the output of the Date class’s toString() method. This means that you cannot use the default DateFormat instances to parse the output of toString() , something that might be useful for things like parsing log data.

The SimpleDateFormat lets you build custom formats. Dates are constructed with a string that specifies a pattern for the dates to be formatted and/or parsed. From the SimpleDateFormat JavaDocs, the characters in Figure 7 can be used in date formats. Where appropriate, 4 or more of the character will be interpreted to mean that the long format of the element should be used, while fewer than 4 mean that a short format should be used.

SymbolMeaningTypeExample
GEraText“GG” -> “AD”
yYearNumber“yy” -> “03″
“yyyy” -> “2003″
MMonthText or Number“M” -> “7″
“M” -> “12″
“MM” -> “07″
“MMM” -> “Jul”
“MMMM” -> “December”
dDay in monthNumber“d” -> “3″
“dd” -> “03″
hHour (1-12, AM/PM)Number“h” -> “3″
“hh” -> “03″
HHour (0-23)Number“H” -> “15″
“HH” -> “15″
kHour (1-24)Number“k” -> “3″
“kk” -> “03″
KHour (0-11 AM/PM)Number“K” -> “15″
“KK” -> “15″
mMinuteNumber“m” -> “7″
“m” -> “15″
“mm” -> “15″
sSecondNumber“s” -> “15″
“ss” -> “15″
SMillisecond (0-999)Number“SSS” -> “007″
EDay in weekText“EEE” -> “Tue”
“EEEE” -> “Tuesday”
DDay in year (1-365 or 1-364)Number“D” -> “65″
“DDD” -> “065″
FDay of week in month (1-5)Number“F” -> “1″
wWeek in year (1-53)Number“w” -> “7″
WWeek in month (1-5)Number“W” -> “3″
aAM/PMText“a” -> “AM”
“aa” -> “AM”
zTime zoneText“z” -> “EST”
“zzz” -> “EST”
“zzzz” -> “Eastern Standard Time”
Excape for textDelimiter“‘hour’ h” -> “hour 9″
Single quoteLiteral“ss”SSS” -> “45’876″

Figure 7. Syntax elements for SimpleDateFormat

Note that you will generally never want to use single-digit minutes, seconds, or milliseconds, even though these are supported by SimpleDateFormat (“m”, “s”, “S”).

A Gu >Last modified: October 20, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Introduction

In this tutorial, we’ll be taking an in-depth tour of the SimpleDateFormat class.

We’ll take a look at simple instantiation and formatting styles as well as useful methods the class exposes for handling locales and time zones.

Now, before getting started, let’s keep in mind SimpleDateFormat is not thread-safe. So taking appropriate precautions in concurrent environments is left to developers.

2. Simple Instantiation

First, let’s look at how to instantiate a new SimpleDateFormat object.

There are 4 possible constructors – but in keeping with the name, let’s keep things simple. All we need to get started is a String representation of a date pattern we want.

Let’s start with a dash-separated date pattern like so:

This will correctly format a date starting with the current day of the month, current month of the year, and finally the current year. We can test our new formatter with a simple unit test. We’ll instantiate a new SimpleDateFormat object, and pass in a known date:

In the above code, the formatter converts milliseconds as long into a human readable date – the 24th of May, 1977.

2.1. Factory Methods

Although SimpleDateFormat is a handy class to quickly build a date formatter, we’re encouraged to use the factory methods on the DateFormat class getDateFormat(), getDateTimeFormat(), getTimeFormat().

The above example looks a little different when using these factory methods:

As we can tell from above, the number of formatting options is pre-determined by the fields on the DateFormat class. This largely restricts our available options for formatting which is why we’ll be sticking to SimpleDateFormat in this article.

3. Parsing Dates

SimpleDateFormat and DateFormat not only allow us to format dates – but we can also reverse the operation. Using the parse method, we can input the String representation of a date and return the Date object equivalent:

It’s important to note here that the pattern supplied in the constructor should be in the same format as the date parsed using the parse method.

4. Date-Time Patterns

SimpleDateFormat supplies a vast array of different options when formatting dates. While the full list is available in the JavaDocs, let’s explore some of the more commonly used options:

LetterDate ComponentExample
MMonth12; Dec
yyear94
dday23; Mon
Hhour03
mminute57

The output returned by the date component also depends heavily on the number of characters used within the String. For example, let’s take the month of June. If we define the date string as:

Then our result will appear as the number code – 06. However, if we add another M to our date string:

Then our resulting formatted date appears as the word Jun.

5. Applying Locales

The SimpleDateFormat class also supports a wide range of locales which is set when the constructor is called.

Let’s put this into practice by formatting a date in French. We’ll instantiate a SimpleDateFormat object whilst supplying Locale.FRANCE to the constructor.

By supplying a given date, a Wednesday afternoon, we can assert that our franceDateFormatter has correctly formatted the date. The new date correctly starts with Vendredi -French for Wednesday!

It’s worth noting a little gotcha in the Locale version of the constructor – whilst many locales are supported, full coverage is not guaranteed. Oracle recommends using the factory methods on DateFormat class to ensure locale coverage.

6. Changing Time Zones

Since SimpleDateFormat extends the DateFormat class, we can also manipulate the time zone using the setTimeZone method. Let’s take a look at this in action:

In the above example, we supply the same Date to two different time zones on the same SimpleDateFormat object. We’ve also added the ‘Z’ character to the end of the pattern String to indicate the time zone differences. The output from the format method is then logged for the user.

Hitting run, we can see the current times relative to the two time zones:

7. Summary

In this tutorial, we’ve taken a deep dive into the intricacies of SimpleDateFormat.

We’ve looked at how to instantiate SimpleDateFormat as well as how the pattern String impacts how the date is formatted.

We played around with changing the locales of the output String before finally experimenting with using time zones.

As always the complete source code can be found over on Github.

Формат даты с SimpleDateFormat Java

У меня есть строка даты как

Я пытаюсь разобрать его с помощью этого SimpleDateFormat

именно такой образ:

Это дает мне разбор ошибки, как:

Как я могу получить дату в указанном выше простом формате даты из строки

5 Ответов

Я подозреваю, что вы не совсем понимаете концепцию SimpleDateFormat.

После определения шаблона с помощью :

valueDateFormat может анализировать объект даты в соответствии с ним, он не берет только строку, которую вы имеете, и преобразует ее. он принимает объект даты.

Ваша строка даты («Wed Jul 01 08:16:13 PDT 2015») не соответствует вашему шаблону («yyyy-MM-dd hh:mm:ss»)

Напишите правильный шаблон, который соответствует строке даты (сначала идет день недели, чем месяц в году и т. д.)

Для таких форматов я создал вспомогательный метод:

Он возвращает объект даты из строки даты, так что вы можете отформатировать строку следующим образом:

И после этого вы можете легко отформатировать заданную переменную даты.

Похожие вопросы:

у меня есть проблема с форматированием строки даты в определенный формат. Вот мой код: Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat(yyyy-MM-dd); // Get current.

Мне нужно преобразовать объект Java Date в строку, которая имеет тот же формат, что и JavaScript Dates, когда они преобразуются в строку. На нашем сервере у нас есть JavaScript дат, которые являются.

Есть идеи, что происходит с этим кодом, что даты не совпадают? Сначала печатается 20 December 2017, а затем дата с новым format:2017-01-01. SimpleDateFormat formatter = new SimpleDateFormat(d MMMM.

Что не так с этим форматом, комментируемый формат выбрасывает исключение , Пожалуйста, помогите мне с этим dd и DD в формате java для даты. SimpleDateFormat dformat = new SimpleDateFormat(yyyyddmm);.

Есть ли возможность назначить дату SQL напрямую вместо преобразования через SimpleDateFormat и разбора на дату sql. Я читаю несколько полей даты из файла, скажем, 03/09/2017, и у меня также есть его.

Я хочу преобразовать формат из yyyyMMdd в ccyyMMdd simpledateformat в java. Я получаю c как незаконный символ в java. Пожалуйста, помогите мне найти раздел для преобразования в формат ccyyMMdd в.

В java, как написать этот формат даты? Dec 17 2011 07:37:55:000PM SimpleDateFormat sdf = new SimpleDateFormat(M W yyyy hh:mm:ss:SSSa); // failed Я пробовал этот формат, он не работает. Пожалуйста.

Есть ли общий способ преобразовать формат даты SimpleDateFormat в регулярное выражение в Java?

Я использую JDBC & Java Swing UI и там я использовал SqLite DB. Здесь у меня есть компонент java, который является jCalender для даты пикапа & я выбираю дату в строку. Сначала я конвертирую.

Я получаю формат даты ответа, как 11:10 AM Thursday — March, 02 2017 . я пробовал, как это String time = 11:10 AM Thursday — March, 02 2017 try < Date cDate = new SimpleDateFormat(hh:mm aa EEE -.

Читать еще:  Java get current directory
Ссылка на основную публикацию