自用java学习笔记
Date类可以创建对象,Calendar类是抽象类,方法是静态的
Date常用SimpleDateFormat类的方法进行格式变换
Calendar创建日历的方法和new一个对象不同,用getInstance方法返回一个Calendar变量
Date测试代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
private DateUtil(){}
// 私有构造方法,外界无法创建对象
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 date = sdf.parse(s);
return date;
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) throws ParseException {
// date类获取时间戳,进行格式转换
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String s = sdf.format(d);
System.out.println(s);
String ss = "2048-08-09 11:11:11";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(ss);
System.out.println(dd);
// 用工具类输出日期
String format = "yyyy-MM-dd HH:mm:ss";
System.out.println(DateUtil.dateToString(d, format));
System.out.println(DateUtil.stringToDate(ss, format));
}
}
Calendar测试代码:
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
// calendar类可以做日期加减法,不需要考虑闰年
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c .get(Calendar.MONTH)+1;
// 月份从0开始计,要+1
int date = c.get(Calendar.DATE);
System.out.println(year +"年"+ month +"月"+ date+"日");
c.add(Calendar.YEAR, -3);
year = c.get(Calendar.YEAR);
month = c .get(Calendar.MONTH)+1;
// 月份从0开始计,要+1
date = c.get(Calendar.DATE);
System.out.println(year +"年"+ month +"月"+ date+"日");
c.set(2048,11,11);
// 注意月份,写的11月份实际指的12月份
year = c.get(Calendar.YEAR);
month = c .get(Calendar.MONTH)+1;
date = c.get(Calendar.DATE);
System.out.println(year +"年"+ month +"月"+ date+"日");
}
}
Calendar计算输入年份2月的天数:
import java.util.Calendar;
import java.util.Scanner;
public class CalendarTest {
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);
// 注意月份,要查2月多少天要用3月1日减去1天,calendar里2月实际是3月
c.add(Calendar.DATE, -1);
int date = c.get(Calendar.DATE);
System.out.println(date +"天");
}
}