Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet88/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   84   85   86   87   88   89   90   91   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Date formatting is a common concern when it comes to any program. People like to 
see their dates in a certain format for different situations. The Java language contains a 
couple of handy utilities for properly formatting date-time data. Specifically, the newer 
API includes the DateTimeFormatter class, and previous editions of Java SE include the 
SimpleDateFormat class, each of which can come in handy for performing formatting 
processes.
The DateTimeFormatter class is a final class with the primary purpose of printing 
and formatting date-time objects. To obtain a DateTimeFormatter that can be applied to 
objects, call the DateTimeFormatter.ofPattern() method, passing the string-based pattern 
representing the desired output. The SimpleDateFormat class was created in previous 
editions of Java, so you don’t have to perform manual translations for a given date.
Note different date formats are used within different locales, and the 
SimpleDateFormat class facilitates locale-specific formatting.
To use the class, an instance must be instantiated either by passing a string-based 
pattern as an argument to the constructor or by passing no argument to the constructor 
at all. The string-based pattern provides a template that should be applied to the given 
date, and then a string representing the date in the given pattern style is returned. A 
pattern consists of many different characters strung together.
Any pattern characters can be placed together in a string and then passed to the 
SimpleDateFormat class. If the class is instantiated without passing a pattern, the pattern 
can be applied later using the class’s applyPattern() method. The applyPattern() 
method also comes in handy when you want to change the pattern of an instantiated 
SimpleDateFormat object, as seen in the solution to this recipe. The following excerpts of 
code demonstrate the application of a pattern.
SimpleDateFormat dateFormatter1 = new SimpleDateFormat("MMMMM dd yyyy");
dateFormatter1.applyPattern("MM/dd/YY hh:mm:ss");
Once a pattern has been applied to a SimpleDateFormat object, a long value 
representing time can be passed to the SimpleDateFormat object’s format() method. 
The format() method returns the given date\time formatted using the applied pattern. 
The string-based result can then be used however your application requires.
Chapter 4 Numbers aNd dates


147

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   84   85   86   87   88   89   90   91   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling