- 案例:日期工具类
需求:定义一个日期工具类(DateUtils),包含两个方法:把日期转换为指定格式的字符串;把字符串解析为指定格式的日期,然后定义一个测试类(DateDemo),测试日期工具类的方法。
分析:
(1)定义日期工具类(DateUtils)
(2)定义一个方法dateToString,用于把日期转化为指定格式的字符串
返回值类型:String
参数:Date date,String format
(3)定义一个方法stringToDate,用于字符串解析为指定格式的日期
返回值类型:Date
参数:String s,String format
(4)定义测试类DateDemo,调用日期工具类中的方法
完整代码:
package integer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
private DateUtils(){}
public static String dateToString(Date date, String format){
SimpleDateFormat sdf = new SimpleDateFormat(format);
String s = sdf.format(date);
return s;
}
public static Date stringToDate(String s,String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d = sdf.parse(s);
return d;
}
}
package integer;
import java.text.ParseException;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) throws ParseException {
Date d = new Date();
String s1 = DateUtils.dateToString(d, "yyyy年MM月dd日 HH:mm:ss");
System.out.println(s1);
String s2 = DateUtils.dateToString(d, "yyyy年MM月dd日");
System.out.println(s2);
String s = "2021-03-30 11:11:11";
Date dd = DateUtils.stringToDate(s, "yyyy-MM-dd HH:mm:ss");
System.out.println(dd);
}
}
运行结果:
2021年03月26日 18:25:27
2021年03月26日
Tue Mar 30 11:11:11 CST 2021
- 案例:二月天
需求:获取任意一年的二月有多少天
分析:
(1)键盘录入任意的年份
(2)设置日历对象的年、月、日
年:来自于键盘录入
月:设置为3月,月份是从0开始的,所以设置值是2
日:设置为1日
(3)3月1日往前推一天,就是2月的最后一天
(4)获取这一天输出即可
完整代码:
package integer;
import java.util.Calendar;
import java.util.Scanner;
public class twoyue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份:");
int year = sc.nextInt();
Calendar c = Calendar.getInstance();
c.set(year, 2, 1);
c.add(Calendar.DATE, -1);
int date = c.get(Calendar.DATE);
System.out.println(year + "年的2月有" + date + "天");
}
}
运行结果:
请输入年份:
2008
2008年的2月有29天