Tình huống
Input: Cho chuỗi
“2023-11-22”
Output:
Day: 22
Month: 11
Year: 2023
Cách 1: Dùng class LocalDate
Bước 1: Convert String thành dạng Datetime và format lại nếu cần
Convert String thành dạng Datetime bằng cách nào?
⇒
LocalDate currentDate = LocalDate.
parse(”2023-11-22”)
Nếu cần format lại định dạng thì sao?
DateTimeFormatter
myFormatObj =
DateTimeFormatter
.ofPattern(”dd-MM-yyyy HH:mm:ss”)
Bước 2: getDayOfMonth, getMonth, getYear
int day = currentDate.
getDayOfMonth()
;
Month month = currentDate.
getMonth()
;
int year = currentDate.
getYear()
;
Cách 2: Dùng class Calendar trong Java
Bước 1: Tạo 1 object Calendar
Calendar cal = new GregorianCalendar(2023,11,22);
GregorianCalendar là lịch dương
Bước 2: Dùng hàm get
int day = cal.
get
(Calendar.DAY_OF_MONTH);
int month= cal.
get
(Calendar.MONTH);
int year = cal.
get
(Calendar.YEAR);
Cách 3: Dùng String.split()
Ví dụ cho
String str = “Full name: Nguyen Ngoc Lam Thu”
String [] arr = str.
split(”:”)
;
Output:
[”Full name”,”Nguyen Ngoc Lam Thu”]
Còn một loại split nữa có 2 tham số
split(regex, limit)
Ví dụ:
String str = “boo:and:foo”
String[] str1= str.split(”o”,2);
Regex là viết tắt của Regular Expression: biểu thức chính quy.
Limit có thể dương, bằng 0 hoặc âm.
Thế limit để làm gì?
- Nếu limit là 2, tức là áp dụng 2-1 = 1 lần, độ dài mảng nhận được không được lớn hơn 2
⇒ Output:
[”b”, ”o:and:foo”]
- Limit là 3, tức là áp dụng 3-1 = 2 lần, độ dài mảng nhận được không được lớn hơn 3
⇒ Output:
[”b”, ”” ,”:and:foo”]
- Tương tự limit 4, áp dụng 3 lần, độ dài mảng không quá 4
⇒ Output:
[”b”, ”” , ”:and:f” ,”o”]
Nếu limit <0 ⇒ tức là áp dụng nhiều lần nhất có thể, mảng có kích thước bất kỳ
Nếu limit =0 ⇒ áp dụng nhiều lần nhất có thể, mảng có kích thước bất kỳ, chuỗi trống sẽ bị add an element holding one space
Ví dụ: Cho chuỗi “geekss@for@geekss”
regex: “s”
limit: “-2”
Output:
[”geek”, ”” , ”” , ”@for@geek” , ”” , ””]
limit: “0”
Output:
[”geek”, ”” , ”@for@geek” ]
Bài tập
Write a Java program to print the current system date and formats it as a string in the pattern "yyyy/MM/dd"
import java.time.LocalDate; import java.time.format.DateTimeFormatter; class Local_Date { publicstaticvoid main(String Args[]) { LocalDate localDate = LocalDate.now(); System.out.println(localDate); // Output: 2024-01-19 (yyyy-MM-dd) => yyyy/MM/dd? DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); String d = formatter.format(localDate); System.out.println("New string:"); System.out.println(d); } }
Write a Java program to print the current system LocalTime HH:mm:ss
import java.time.LocalTime; import java.time.format.DateTimeFormatter; class Local_Time { publicstaticvoid main(String Args[]) { String t; LocalTime lt = LocalTime.now(); DateTimeFormatter formatterLocalTime = DateTimeFormatter.ofPattern("HH:mm:ss"); t = formatterLocalTime.format(lt); System.out.println("HH:mm:ss = " + t); } }
Write a Java program to display combine local datetime in a single object
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; class Combine_Local_DateTime { publicstaticvoid main(String[] args) { LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //Output: 2024-01-19T10:00:16.137175 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a"); String d = formatter.format(localDateTime); System.out.println(d); //Output: 2024-01-19 10:01:09 AM } }
Write a Java program to extract date, time from the date string
import java.util.*; import java.text.*; public class Extract_DateTime { publicstaticvoid main(String[] args) { // chuyển từ String sang Date String str_date = "2014-06-08 10:30:25"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str_date); // chuyển từ Date sang String String newstr_date = new SimpleDateFormat("MM/dd/yyyy, H:mm:ss").format(date); System.out.println(newstr_date); } }
Write a Java program to calculate your age
import java.time.*; class Calculate_Age { publicstaticvoid main(String[] args) { LocalDate pdt = LocalDate.of(1992,03,9); LocalDate tdt = LocalDate.now(); Period diff = Period.between(pdt, tdt); System.out.println("Date of Birth : "+pdt); System.out.println("Age : "+diff.getYears()); System.out.println("Years : "+diff.getYears()); System.out.println("Months : "+diff.getMonths()); System.out.println("Days : "+diff.getDays()); } }
Write a Java Program to Compare time using compareTo() method
The compareTo() method returns an integer value indicating the order of the two LocalTime objects.
If the first object is later than the second object, the method returns a positive integer.
If the first object is earlier than the second object, the method returns a negative integer.
If the two objects are the same, the method returns zero.
import java.util.*; import java.time.*; publicclass Time_CompareTo { publicstaticvoid main(String[] args) { LocalTime t1; LocalTime t2; LocalTime t3; t1 = LocalTime.of(12, 10, 23); t2 = LocalTime.of(12, 10, 23); t3 = LocalTime.of(10, 45, 46); if (t1.compareTo(t2) > 0) { System.out.println("Time 1 is Later Than Time 2"); } elseif (t1.compareTo(t2) < 0) { System.out.println("Time 2 is Later Than Time 1"); } else{ System.out.println("Time 1 and Time 2 are Same"); } if (t2.compareTo(t3) > 0) { System.out.println("Time 2 is Later than Time 3"); } elseif (t2.compareTo(t3) < 0) { System.out.println("Time 3 is Later than Time 2"); } else{ System.out.println("Time 2 and Time 3 are Same"); } } }
Write a Java program to calculate the difference between two dates in days
First, two Calendar objects are created using the Calendar.getInstance() method, which returns a Calendar object representing the current date and time in the default time zone.
The set() method is used to set the year, month, and day of each Calendar object to the desired values.
The Math.abs() method is used to ensure a positive value.
The TimeUnit.DAYS.convert() method is then used to convert the milliseconds difference to days.
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.concurrent.TimeUnit; class Calculate_Days { publicstaticvoid main(String[] args) { Calendar cal1 = Calendar.getInstance(); cal1.set(2022, 10, 1); Calendar cal2 = Calendar.getInstance(); cal2.set(2023, 10, 1); long Ms = Math.abs(cal1.getTimeInMillis() - cal2.getTimeInMillis()); long Days = Math.abs(TimeUnit.DAYS.convert(Ms, TimeUnit.MILLISECONDS)); System.out.println("Difference in days is: " + Days); } }