Java Dates and Times Flashcards
which package to import to work with date and time classes?
java.time.*
what are the four choices of Date and time usage?
LocalDate, LocalTime, LocalDateTime, ZonedDateTime
LocalDate
No Time, no timezone. Just Date. Eg.., My birthday
LocalTime
No date, no timezone. Just time. Eg..Midnight
LocalDateTime
Contains both date and time, no time zone. Eg.., Stroke of midnight on new years eve.
ZonedDateTime
contains date, time, timezone. Eg.., conference call at 9 a.m. EST
Example of different time zone offsets that can be listed
+02.00 or GMT+2 or UTC+2
Different ways to pass the month value for a date
Either MONTH ENUM(eg.. Month.JANUARY) or pass an int number.
The int starts with 1. Eg.. 1 for January
Month month = Month.JANUARY;
boolean b1=month==1;
boolean b2= month==Month.APRIL;
Output?
b1 does not compile. MONTH is an enum and cannot be compared with int.
b2 returns false as month is JANUARY
What is the first thing to do to get the ZonedDateTime?
We need to get the desired time zone.
How to create a zoned date time?
ZoneId zone = ZoneId.of(“US/Eastern”);
Three approaches to get the ZonedDateTime
- Pass all the values individually.
ZonedDateTime zoneTime = ZonedDateTime.of(2017, 8, 6, 11, 27, 30,200, zone); - Pass the LocalDate, LocaltTme and Zone objects
ZonedDateTime zoneTime = ZonedDateTime.of(LocalDateObject, LocalTimeObject, zone); - Pass the LocalDateTime and zone object.
ZonedDateTime.of(LocalDateTimeObject, zone);
One important thing to consider for ZonedDateTime object Creation
There is no option to pass in the Month Enum
To find the System time zone
ZoneId.systemDefault()
Why we cant invoke a constructor for Date and Time classes
Dates and Time classes have private constructors. We cannot invoke them. We have to use their static methods for any operations.
LocalDate date = new LocalDate(); What will happen
It will not compile
LocalDate date = LocalDate.of(2017, Month.JANUARY, 32);
It throws DateTimeException as it has invalid dates
LocalDate date = LocalDate.of(2020, Month.JANUARY, 20);
date = date.plusMinutes(1);
It does not compile.
We are trying to add the time to the date object.
What are the different approaches to create a period Object?
Period p1 = Period.of(years, months, days); Period p2 = Period.ofDays(1); Period p3 = Period.ofWeeks(weeks); Period p4 = Period.ofMonths(months); Period p5 = Period.ofYears(years);
What is one important catch about Period?
You cannot chain the period methods. If you do it returns the last period operation value with a compile warning, remember that Period is immutable.
If we print the period what is the format it is printed?
Eg,,. Period.of(1, 2, 3)
P1Y2M3D
P -> To show that it is a period measure
1Y -> No of Years with Y indicating the year
2M-> No of Months with M indicating the month
3D-> No of days with D indicating the Days
An important point to remember on displaying the Period?
If any of the values (either Year or month or days) are not available, then they are omitted
Period.ofMonths(3)
P3M
Period.of(0,20,47)
P20M47D. No issues in Period with Days greater than the no of days in month OR MONTH GREATER THAN THE NO OF MONTHS IN A YEAR
Period.ofWeeks(3)
P21D :)
Weeks are not one of the units a Period stores. So, it converts into a number of days and stores them.
What happens when we try to use a Period of Month to LocalTime?
UnsupportedTemporalTypeexception
What is Duration? why we use duration when we have Period?
- Duration is intended for smaller units of time.
2. Period is for Days and more of a time
How does the Period and Duration Outputs starts with?
Period: P
Duration: PT -> Period of Time
What are all the units that can be specified for Duration?
Days, hours, minutes, Seconds, milliseconds, nanoseconds
Different ways of creating the Duration
Duration.ofDays(1); Duration.ofHours(1); Duration.ofMinutes(1); Duration.ofSeconds(1); Duration.ofMillis(1); Duration.ofNanos(1);
What does duration doesnt have on comparing to Period?
It doesnt have the constructor that takes three units
What is another factory method that Duration takes?
A method with number and TemporalUnit
What is temporal Unit
An interface
What is the implementation of TemporalUnit?
ChronoUnit
Where can a Duration and Period can be used?
Period:
- LocalDate
- LocalDateTime
- ZonedDateTime
Duration:
- LocalTime
- LocalDateTime
- ZonedDateTime
What is Instant Class
Instant class represents a specific moment in the GMT time zone
How to get the current time using Instant
Instant instant = Instant.now();
Can we convert a LocalDateTime to Instant? Why?
we cannot convert a localDateTime to instant because, LocalDateTime does not contain a Timezone and Instant contain a time zone in it.
What to keep in mind while doing math Operation on Instant Class
Instant class allows doing Math operation with Days or units lesser than That. If you try to add a week, month or year we get Exceptions
What is the method for add operation in Instant?
plus();
Eg../ Instant.plus(1, Chronounit.DAYS or Hours or any lesser)
How does oracle defines Locale?
A specific geographical or political or cultural region
Locale class is in which package
java.util;
How will you get the Locale of your computer?
Locale locale = Locale.getDefault();
Format for Locale. Which are optional?
two lowercase language code followed by ‘_’ and two uppercase country code letters.
_ and Country codes are optional. You can have only Language code as Locale information.
Three ways of creating a Locale?
- Locale class provides the constants for some of the most commonly used Locales
- Use constructors with Just passing a language
new Locale(“fr”); - Use constructors by passing a language and country code.
new Locale(“hi”, “IN”);
Will java allow you to create Locale with invalid language or country code
Yes. But your program will behave wierdly.
What is the other way to create a Locale apart from the other 3
Using Builder design pattern. It lets you set all the properties that we want to set and let us Build
Eg of using Builder design pattern to create a locale effectively
Locale l1 = new Locale.Builder.
setRegion(“US”).
setLanguage(“en”).
build();
How not to use Locale.Builder?
setting country code with lowercase or language code with Upper case or creating an empty Locale. It causes confusion.
How to change the Locale of the system. Eg..?
Locale locale = new Locale("de", "DE"); locale.setDefault(locale);
What does Resource Bundles contain?
Resource bundles contains the locale specific object to be used by the program. It has map, key vales pair
Which method allows for a default value?
getDefault or get?in Property class
getProperty()
Which class to extend on creating a Java class resource bundle? Explain that class and methods
ListResourceBundle. It is a abstract class leaves one method for subclasses to implement. The method is getContents.
What are the two advantages of having a Java class Resource bundles? and one limitations?
- You can use value type that is not a string
- We can create values for Properties are runtime.
Limits:
1. The key type should be a string though
what are the two methods for creating a resource bundle?
ResourceBundle.getBundle(“name”);
ResourceBundle.getBundle(“name”, locale);
Picking a resource Bundle steps
- Always look for the property files after the matching java class
- Drop one thing at a time if there are no matches. First drop country code and then the language code
- Look at the default Locale at the end
what is the trick for finding a particular value with a key
Java first looks for the key in the most specifi locale.java class and then Locale.properties and then its parent. So It can read values from its parent too.
which package has the class for Number Formatting?
java.text.*;
What is format and parse?
format() -> convert a number into String
parse() -> Convert a string into a number
Do format classes are thread safe?
No, they are not thread safe. Should not save in instance variable or static variables.
What is the exception that parse method throws?
It throws a checkd Exception ParseException
What does parse method does with extra characters while parsing?
The parser method parses only the beginning of the String.If the parser method reaches a character that dos not be parsed, it stopes there and returns the parsed value
NumbarFormat nf = NumberFormat.getInstance(); String one = "456vdgg" String two = "-2.156x10" String three = "xfgfg776" nf.parse(one); nf.parse(two); nf.parse(three); Output?
one = 456;
two = -2.156
three =ParseException because there are no numbers in the beginning of the String.
What is the return value of the Parse method?
Number object. Number is a parent class of Java.lang wrapper class so it can be casted
What is the class used for Formatting Dates? Which package? Which method?
DateTimeFormatter.
java.time.format pacakage.
It can format any type of date and/or time Object.
format() method
Thera res some predefined DateTimeFormatter. Eg?
DateTimeFormatter shortDateTiime = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
What is so special about format() method?
The format method can be declared on both Formatter object and date/time objects.
What happens when we try to format time using DateFormatted?
UnsupportedTemporalTypeException.
What should we do if we want a new Formatter?
DateTimeFormatter df = DateTimeFormatter.ofPattern(“MMMM dd, yyy, hh:mm”);
In using Property class, which overloaded method to use so that if the value of a property is not set, default value that we pass is returned?
Property;s getProperty(key, “default value to be returned if not present”);
What is the limitation of using property file as resource bundle?
It can have the property value only as String.
Note that key will always be String using property file or class file
Example for Using Java resource bundles
import java.util.*;
2: public class Zoo_en extends ListResourceBundle {
3: protected Object[][] getContents() {
4: return new Object[][] {
5: { “hello”, “Hello” },
6: { “open”, “The zoo is open” } };
7: } }
Different NumberFormat Instances?
NumberFormat.getInstance() NumberFormat.getInstance(locale) NumberFormat.getNumberInstance() NumberFormat.getNumberInstance(locale) ================For formatting monetary amounts====================== NumberFormat.getCurrencyInstance() NumberFormat.getCurrencyInstance(locale) ===================For formatting percentages ==========================NumberFormat.getPercentInstance() NumberFormat.getPercentInstance(locale) ======================Rounds decimal values before displaying (not on the exam)======================== NumberFormat.getIntegerInstance() NumberFormat.getIntegerInstance(locale)
How to get all the availableZoneIds?
ZoneId.getAvaliableZoneId()
How to get next Thursday date from Today?
LocalDateTime date = LocalDateTime.now().with(TemporalAdjusters.next(DayOfWeek.THURSDAY));
What is Period or Duration and Instants
Period- Specification of time in Day, week and month
Duration: Minustes, hours
Instants: Instance of time