java 实现判断时间早晚如6:00:00 晚于 4:00:00

写一个比较时间的方法 DateCompare给你,具体看注释,在main方法里面有测试:import java.text.SimpleDateFormat;import java.util.Date;public class TEST {/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {//例如比较当前时间和早上6:00...
java 实现判断时间早晚如6:00:00 晚于 4:00:00
写一个比较时间的方法 DateCompare给你,具体看注释,在main方法里面有测试:
import java.text.SimpleDateFormat;import java.util.Date;public class TEST {/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {//例如比较当前时间和早上6:00String nowTime = new SimpleDateFormat("HH:MM").format(new Date());System.out.println("当前时间为:"+nowTime);System.out.println("与当日06:00相比");int i = DateCompare(nowTime,"06:00","HH:MM");switch (i) {case 0:System.out.println("两个时间相等");break;case 1:System.out.println("当前时间晚于06:00");break;case -1:System.out.println("当前时间早于06:00");break;default:break;}}/** * 根据时间类型比较时间大小 * * @param source * @param traget * @param type "YYYY-MM-DD" "yyyyMMdd HH:mm:ss" 类型可自定义 * @param 传递时间的对比格式 * @return * 0 :source和traget时间相同 * 1 :source比traget时间大 * -1:source比traget时间小 * @throws Exception */public static int DateCompare(String source, String traget, String type) throws Exception {int ret = 2;SimpleDateFormat format = new SimpleDateFormat(type);Date sourcedate = format.parse(source);Date tragetdate = format.parse(traget);ret = sourcedate.compareTo(tragetdate);return ret;}}该方法可以转换时间、日期、具体什么格式可以自定义,
另外如果你是需要做定时任务,推荐使用quartz有java的实现版。
希望对你有帮助。
2014-01-09
import java.util.Calendar;
public class test {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.HOUR_OF_DAY));
}
}
把时间转化为Calenda类型,然后 get(Calendar.HOUR_OF_DAY) 就得到小时了2014-01-09
Calendar类中有after(Object when)方法
判断此 Calendar 表示的时间是否在指定 Object 表示的时间之后,返回判断结果。
before(Object when) 方法
判断此 Calendar 表示的时间是否在指定 Object 表示的时间之前,返回判断结果。
可以试一下!2014-01-09
可以用SimpleDateFormat类设置格式的时间显示参数,然后根据你自己的条件进行比较判断就可以了。2014-01-09
SimpleDateFormat.parse(String).getTime() 应该是这个 转成long比较大小就行2014-01-09
把时间转换为integer,哈哈 我以前用过的....然后int比较2014-01-09
mengvlog 阅读 11 次 更新于 2025-06-19 14:21:29 我来答关注问题0
檬味博客在线解答立即免费咨询

Java相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部