要将 java 字符串与当前时间进行比较,可以遵循以下步骤:创建一个 simpledateformat 对象,指定日期时间格式。将字符串解析为 date 对象。获取当前日期时间。比较两个日期时间,判断相等、大于或小于当前时间。
如何将 Java 字符串与当前时间进行比较
简介要在 Java 中将字符串与当前时间进行比较,可以使用 java.util.Date 类和 java.text.SimpleDateFormat 类。
步骤
创建 SimpleDateFormat 对象:
立即学习“Java免费学习笔记(深入)”;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");登录后复制
注意:指定要比较的日期时间格式,例如 "yyyy-MM-dd HH:mm:ss"。
将字符串解析为 Date 对象:
Date dateFromString = sdf.parse(inputString);登录后复制
获取当前日期时间:
Date currentDate = new Date();登录后复制
比较两个日期时间:
相等:dateFromString.equals(currentDate)
大于:dateFromString.after(currentDate)
小于:dateFromString.before(currentDate)
示例
// 输入字符串日期时间
String inputString = "2023-03-08 13:30:00";
// 创建 SimpleDateFormat 对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将字符串解析为 Date 对象
Date dateFromString = sdf.parse(inputString);
// 获取当前日期时间
Date currentDate = new Date();
// 比较两个日期时间
if (dateFromString.equals(currentDate)) {
System.out.println("输入的日期时间与当前时间相同。");
} else if (dateFromString.after(currentDate)) {
System.out.println("输入的日期时间晚于当前时间。");
} else {
System.out.println("输入的日期时间早于当前时间。");
}登录后复制以上就是java怎么和当前时间比较string的详细内容,更多请关注php中文网其它相关文章!
JamesEreni5 天前
发表在:Java webservice多个参数怎么调用Получи лучшие казинo...
NormanSoacy7 天前
发表在:Java webservice多个参数怎么调用Получи лучшие казинo...
NormanSoacy7 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
DominicNex8 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/reyti...
DominicNex8 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
RobertSor9 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
RobertSor10 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
RobertSor10 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Ofits...
RobertSor15 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Magic...
RichardTrugs19 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/TgWin...