[英]How to compare system's current LocalDateTime with input String date and time
我正在嘗試將當前系統的時間和日期與輸入字符串時間和日期進行比較。 我正在使用LocalDateTime.now()
獲取系統當前時間,並使用DateTimeFormatter
將其格式化為 dd-MM-yyyy HH:mm 模式
static DateTimeFormatter frmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
static LocalDateTime time = LocalDateTime.now();
這是我所擁有的:
System.out.print("Enter the Appointment new Date and Time as dd-mm-yyyy hh:mm : ");
String dateAndTime = input.nextLine();
if (//dateAndTime is before or equals the current system time)
{
System.out.println("The new date and time should be after the current time");
}
else
{
System.out.println("Appointment has been updated");
}
假設您已經解析了LocalDateTime
的輸入,您可以執行以下操作:
if (parsedDateTime.isAfter(LocalDateTime.now())) {
System.out.println("Appointment has been updated");
} else {
System.out.println("The new date and time should be after the current time");
}
請記住,如果parsedDateTime
和LocalDateTime.now()
完全相同, isAfter
將返回 false。
您可以使用解析或格式
Date date = null;
boolean checkdateformat;
try {
SampleDateFormat dateFormat = new SampleDateFormat("yyyy/dd/MM");
dateFormat.setLenient(false);
date = dateFormat.parse("2021/12/02");
} catch (ParseException ex) {
ex.printStackTrace();
}
if (date == null) {
checkdateformat = false;
} else {
checkdateformat = true;
}
System.out.println(checkdateformat);
or use format
public static void main(String[] args) throws ParseException {
String input = "2021/12/31";
boolean checkdateformat;
if (input.matches("([0-9]{4})/([0-9]{2})/([0-9]{2})")) // for yyyy/MM/dd format
checkdateformat = true;
else
checkdateformat = false;
System.out.println(checkformat);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.