此为JDK7中
时间Date:
public class test {
public static void main(String [] arg) {
Date d1=new Date(0L);
System.out.println(d1);
}
}
SimpleDateFormat:
把时间变成喜欢的格式;把字符串表示的时间变成Date对象。
String format(Date date)——格式化
public Date parse(String source)——解析:字符串变为Date
public class test {
public static void main(String [] arg) {
SimpleDateFormat s=new SimpleDateFormat();
Date d=new Date(0L);
String t=s.format(d);
System.out.println(t);
}
}
指定格式:
SimpleDateFormat s1=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");//指定格式
String t1=s1.format(d);
System.out.println(t1);
parse:
public class test {
public static void main(String [] arg) throws ParseException {
String s="2024-05-21 11:15:20";
SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=sd.parse(s);
System.out.println(date);
}
}
练习:秒杀活动:某品牌秒杀时间:2023年11月11日 0:0:0到2023年11月11日 0:10:0
小明下单付款时间在2023年11月11日 0:05:0,请问在活动时间内吗?
public class test {
public static void main(String [] arg) throws ParseException {
String start="2023年11月11日 0:0:0";
String end="2023年11月11日 0:10:0";
String s="2023年11月11日 0:05:0";
SimpleDateFormat sd=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date dstart=sd.parse(start);
Date dend=sd.parse(end);
Date d=sd.parse(s);
if(d.getTime()>=dstart.getTime()&&d.getTime()<=dend.getTime()) {
System.out.println("秒杀成功");
}else {
System.out.println("秒杀失败");
}
}
}
Calendar:代表系统当前时间的日历对象,可以单独修改,获取时间中的年月日。
Calendar.getInstance();——创建对象
public int get(int field)——去日期中某个字段信息
public void set(int field,int value)——修改日历的某个字段信息
public void add(int field,int amount)——为某个字段增加/减少指定的值