Java Fumana uMhla woMhla wangoku

Ufumana njani umhla kunye nexesha langoku kwiJava? Kule tutorial siza kujonga iindlela ezintathu ezahlukeneyo kwiJava 8.

Iiklasi ezisetyenziselwa ukubonisa umhla nexesha zi LocalDate, LocalTime, LocalDateTime.



Fumana uMhla wangoku

I LocalDate iklasi lisetyenziselwa ukumela umhla.


GetCurrentDate.java

import java.time.LocalDate; public class GetCurrentDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println(now.toString());
} }

Iziphumo:


2020-02-07

Umhla ohleliweyo

Singasebenzisa DateTimeFormatter iklasi ukufomatha umboniso womhla. Umzekelo ukubonisa umhla wangoku kwifomathi ye yyyy/mm/dd sisebenzisa:



import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class GetCurrentDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println(now.format(DateTimeFormatter.ofPattern('yyyy/MM/dd')));
} }

Iziphumo:

2020/02/07

LocalDate iklasi inezinye iindlela eziluncedo esinokuzisebenzisa ukufumana iinkcukacha ezithe kratya malunga nomhla wangoku:

getDayOfWeek()

Iziphumo:


getDayOfMonth()

Fumana ixesha langoku

I getDayOfYear() iklasi imele ixesha.

import java.time.LocalDate; public class GetCurrentDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println('Today's date: ' + now.toString());
System.out.println('Day of week: ' + now.getDayOfWeek().toString());
System.out.println('Day of month: ' + now.getDayOfMonth());
System.out.println('Day of year: ' + now.getDayOfYear());
} }

Today's date: 2020-02-07 Day of week: FRIDAY Day of month: 7 Day of year: 38 Phawula:Singasebenzisa DateTimeFormatter ukufomatha umboniso wexesha.

Iziphumo:

LocalTime

GetCurrentTime.java iklasi ikwanazo neendlela eziluncedo zokufumana ulwazi ngakumbi malunga nexesha langoku:


import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class GetCurrentTime {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println('Time now: ' + now.toString());
System.out.println('Formatted time: ' + now.format(DateTimeFormatter.ofPattern('HH:mm:ss')));
} }

Iziphumo:

Time now: 00:02:53.313 Formatted time: 00:02:53

Fumana ixesha loMhla wangoku

Ukufumana umhla wangoku kwaye ixesha, sinokusebenzisa LocalTime iklasi

import java.time.LocalTime; public class GetCurrentTime {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println('Current hour: ' + now.getHour());
System.out.println('Current minute: ' + now.getMinute());
System.out.println('Current second: ' + now.getSecond());
} }

Iziphumo:

Current hour: 0 Current minute: 10 Current second: 16