Làm sạch dữ liệu bằng Java
Dennis Lee
Software Engineer
| Tên sản phẩm | Ngày nhận |
|---|---|
| Ớt chuông | 3/1/25 |
| Dầu thực vật | 04-01-2025 |
| Phô mai | 2025.06.01 |
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
// Chỉ định định dạng mong đợi (M/d/yy) DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");// Chuyển chuỗi thành LocalDate LocalDate date = LocalDate.parse("3/1/25", formatter); System.out.println("Ngày chuyển từ chuỗi: " + date);
Date converted from string: 2025-03-01
String[] dates = {"3/1/25", "04-01-2025", "2025.06.01"}; // Các định dạng đầu vào DateTimeFormatter[] formatters = { // Định dạng mong đợi trong đầu vào DateTimeFormatter.ofPattern("M/d/yy"), // Tháng/ngày không thêm số 0 DateTimeFormatter.ofPattern("MM-dd-yyyy"), // Tháng/ngày có số 0 đầu DateTimeFormatter.ofPattern("yyyy.MM.dd") };System.out.println("Ngày đã chuẩn hóa:"); for (int i = 0; i < dates.length; i++) { LocalDate date = LocalDate.parse(dates[i], formatters[i]); // Chuyển sang ngày System.out.println("Format " + dates[i] + " as " + date1); }
Standardized dates:
Format 3/1/25 as 2025-03-01
Format 04-01-2025 as 2025-04-01
Format 2025.06.01 as 2025-06-01
// Ví dụ ngày đầu vào LocalDate date = LocalDate.parse("2025-03-01"); // Muốn hiển thị là March 1, 2025 DateTimeFormatter displayFormat = DateTimeFormatter.ofPattern("MMMM d, yyyy");// Định dạng ngày theo mẫu String formattedDate = date.format(displayFormat); System.out.println("Formatted date: " + formattedDate);
Formatted date: March 1, 2025
import java.time.ZoneId;
LocalDate date = LocalDate.parse("2025-03-01"); // Ví dụ ngày đầu vàoZonedDateTime nyTime = date.atStartOfDay(ZoneId.of("America/New_York")); // Chuyển cùng thời điểm sang giờ LA ZonedDateTime laTime = nyTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));System.out.println("New York time: " + nyTime); System.out.println("Los Angeles time: " + laTime);
New York time: 2025-03-01T00:00-05:00[America/New_York]
Los Angeles time: 2025-02-28T21:00-08:00[America/Los_Angeles]
// Sai: Trích tháng bằng thao tác chuỗi System.out.println("Does 3/1/25 start with 3? " + "3/1/25".startsWith("3")); System.out.println("Does 03-15-25 start with 3? " + "03-15-25".startsWith("3"));// Đúng: Dùng ngày tháng chuẩn hóa DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-d-yy"); LocalDate date = LocalDate.parse("03-15-25", formatter); // Chuyển sang ngày System.out.println("Tháng và năm của 03-15-25: " + date.getMonth() + " " + date.getYear()); // Lấy tháng/năm
Does 3/1/25 start with 3? true Does 03-15-25 start with 3? falseMonth and year of 03-15-25: MARCH 2025
Các import chính
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.ZoneId;
DateTimeFormatter.ofPattern()LocalDate.parse()ZoneId.of(), .withZoneSameInstant().format()LocalDate.parse() thay vì thao tác chuỗi (.startsWith())Làm sạch dữ liệu bằng Java