11package com .amir .api .time ;
22
33import java .time .Instant ;
4+ import java .time .LocalDate ;
45import java .time .ZoneId ;
56import java .time .ZonedDateTime ;
7+ import java .time .format .DateTimeFormatter ;
8+ import java .time .format .DateTimeFormatterBuilder ;
9+ import java .time .temporal .TemporalAccessor ;
610import java .util .Calendar ;
711import java .util .Date ;
812import java .util .GregorianCalendar ;
@@ -26,6 +30,10 @@ public class Date2TimeDemo {
2630 TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of("Asia/Manila")));
2731 time-package api happlily working with specified TimeZone.
2832
33+ SimpleDateFormat we used for lagecy with java.util.Date
34+
35+
36+
2937 Time API
3038 -------------
3139 LocalDate -> deals with date only
@@ -37,33 +45,34 @@ public class Date2TimeDemo {
3745 you can get Date object from TimeAPI using toInstant and vice versa.
3846
3947 Instant is availabe in Date,Calendar & Time API also.
40- *
48+ * alternative for SimpleDateFormat is DateTimeFormatter.
49+ *
50+ * you can use format method of time api or format method of DateTimeFormatter class.
51+ *
4152 *
4253 */
4354
4455
4556
4657 public static void main (String [] args ) {
4758
48- // TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of("Asia/Manila")));
59+ TimeZone .setDefault (TimeZone .getTimeZone (ZoneId .of ("Asia/Manila" )));
4960 ZonedDateTime now = ZonedDateTime .now ();
5061 System .out .println (now );
51- ZonedDateTime addedOne = now .plusHours (2 );
52- Date from = Date .from (addedOne .toInstant ());
53- System .out .println (from .after (new Date ()));
62+ //ZonedDateTime addedOne = now.plusHours(2);
5463
55-
56- // Time API
57- //--------------
64+ String format = DateTimeFormatter .ISO_OFFSET_DATE_TIME .format (now );
65+ System .out .println (now .format (DateTimeFormatter .ISO_OFFSET_DATE_TIME ));
5866
59- Calendar cal = Calendar .getInstance ();
60- Date date = new Date ();
61- Instant now2 = Instant .now ();
62- Date from2 = Date .from (now2 );
63- ZonedDateTime zdt = ZonedDateTime .ofInstant (now2 , TimeZone .getTimeZone ("Asia/Manila" ).toZoneId ());
64- System .out .println (from2 );
65- System .out .println (zdt );
67+
68+ DateTimeFormatter dtf = DateTimeFormatter .ofPattern ("YYYY-MM-dd" );
69+ System .out .println (now .format (dtf ));
6670
71+ LocalDate date = LocalDate .now ();
72+ DateTimeFormatter formatter = DateTimeFormatter .ofPattern ("yyyy-MM-dd" );
73+ String text = "2022-03-19" ;
74+ LocalDate parsedDate = LocalDate .parse (text , formatter );
75+ System .out .println (parsedDate );
6776
6877 }
6978}
0 commit comments