Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Suppose you have a String date in the yyyy/mm/dd


Download 1.52 Mb.
Pdf ko'rish
bet91/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   87   88   89   90   91   92   93   94   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Suppose you have a String date in the yyyy/mm/dd
format. How can you obtain a LocalDate object
corresponding to such a date?
Answer:
The code below demonstrates converting a String date in
yyyy/mm/dd format to a LocalDate:
String strDate = “2012/10/11”;
LocalDate date = LocalDate.
parse(strDate, DateTimeFormatter.
ofPattern(“yyyy/MM/dd”));
System.out.println(date);
The LocalDate has a parse() method which can be used to
convert a String Date to a LocalDate object. The parse()
method accepts a LocalDate in the yyyy–MM–dd format. In the
scenario above, the date is in the yyyy/MM/dd format, so
parse() method will not work as it is. However, there is an
overloaded version of the parse() method which accepts a


240.
241.
DateTimeFormatter instance in addition to the String date. A
DateTimeFormatter can be created via the static
DateTimeFormatter.ofPattern() method. This method
accepts as parameter a String corresponding to the desired data
format. Here, the code creates a DateTimeFormatter that can
parse a date in the yyyy/mm/dd format. So, this code prints the
output shown below:
2012–10–11
What is the output of the following code snippet?
LocalDateTime dateTime = LocalDateTime.parse(“2014–12–
28T08–45–00”);
dateTime = dateTime.withYear(1998);
System.out.println(dateTime);
Answer:
The code above first creates a LocalDateTime instance. It then
invokes the dateTime.withYear() method. This method
updates the year component on the LocalDateTime on which it
is invoked to the specified year. So, in this case, it updates the
year in dateTime to 1998 and assigns the result
to the dateTime object. So, this code prints the output shown
below:
1998–12–28T08–45

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   87   88   89   90   91   92   93   94   ...   171




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