SimpleDateFormat
// 格式化时间
SimpleDateFormat format = new SimpleDateFormat("YYYY年MM月dd日");
// 获取当前时间
Date date = new Date();
// 将当前时间传入 format
String format1 = format.format(date);
System.out.println(format1);
// 1999 3 26 09:00:00
String str = "1999-3-26 09:00:00";
// 字符串解析成日期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parseDate = simpleDateFormat.parse(str);
System.out.println(parseDate);
// 日期格式化为想要的字符串
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = simpleDateFormat1.format(parseDate);
System.out.println(format);
需求:
肯打鸡品牌有一个秒杀活动:
活动开始时间为:2020年11月11日 0:0:0
活动结束时间为:2020年11月11日 0:10:0
现在,有两名同学参加了活动,小贾下单并付款的时间为:2020年11月11日 0:03:47。
小皮下单并付款的时间为:2020年11月11日 0:10:11
要求:
用代码说明这两位同学有没有参加上秒杀活动?
分析:
* 判断下单时间是否在开始到结束的范围内。
* 把字符串形式的时间变成毫秒值。
解析:
public class Test4 {
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
// 开始时间
Date startDate = simpleDateFormat.parse("2020年11月11日 00:00:00");
// 结束时间
Date endDate = simpleDateFormat.parse("2020年11月11日 00:10:00");
// end -start 时间差 活动范围时间 poor
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long poor = endTime - startTime;
// 小贾下单时间
Date parse = simpleDateFormat.parse("2020年11月11日 00:3:47");
// 下单时间转为毫秒值
long time = parse.getTime();
// 下单时间 - 活动开始时间
long xiaoTime = time - startTime;
method(xiaoTime, poor);
// 小皮下单时间
Date parse1 = simpleDateFormat.parse("2020年11月11日 00:10:11");
long time1 = parse1.getTime();
long xiaopiTime = time1 - startTime;
method(xiaopiTime, poor);
}
public static void method(long time, long poor) {
if (time <= poor && time > 0) {
System.out.println("在秒杀时间内");
} else {
System.out.println("不在秒杀时间内");
}
}
}
Calendar
注意细节:
1,负数往前减,正数往后加。
2,如果时间为12月,再往后加一个月,会跳到下一年的1月。
public static void main(String[] args) {
Calendar instance = Calendar.getInstance();
// 向前减一年
instance.add(Calendar.YEAR, -1);
int year = instance.get(Calendar.YEAR);
// 向前减10天
instance.add(Calendar.DAY_OF_MONTH, -10);
int month = instance.get(Calendar.MONTH);
int day = instance.get(Calendar.DAY_OF_MONTH);
int week = instance.get(Calendar.DAY_OF_WEEK);
// 星期
String s = get(week);
System.out.println(year + "年" + (month + 1) + "月" + day + "日" + s);
}
public static String get(int week) {
String[] arr = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
return arr[week];
}
}