关于日期第一个想到的就是Date这个类,而在使用时一般紧跟着就会用到SimplDateFormat来格式化
package io;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
public class SystemDemo {
public static void main(String[] args) throws Exception{
//Date类,日期时间相关的获取,但大部分方法已过时
Date d = new Date();
System.out.println(d);
//将格式封装到SimpleDateFormat对象中,然后调用该对象的format方法格式化Date对象
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
System.out.println(sdf.format(d));
//Calendar类,日历,封装了一些常量用于操作日期的属性,比如Calendar.YEAR,Calendar.MONTH
Calendar c = Calendar.getInstance();
System.out.println(c);
}
}
接着学习了日期的另一个类Calendar,学到这里的时候突然想到了前几天的一个关于日历的练习,这里用Calendar重新写了一遍
package test;
import java.util.Calendar;
public class CalendarTest2 {
//获得当天日期
private static Calendar c = Calendar.getInstance();
public static void getCurrentDate(){
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH)+1;
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("今天是:"+year+"-"+month+"-"+day);
// System.out.println(c);
}
//获取当前月份的日历
public static void getCurrentCalendar(){
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH)+1;
int day = c.get(Calendar.DAY_OF_MONTH);
//打印今天的日期
System.out.println("今天是:"+year+"年"+month+"月"+day+"日");
//设置日期为下个月1号
if(month!=12){
c.set(year,month,1);
}else{
c.set(year,0,1);
}
//设置日期为该月的最后一天
c.add(Calendar.DAY_OF_MONTH,-1);
//获取该月一共有多少天
day = c.get(Calendar.DAY_OF_MONTH);
//设置日期为该月的第一天
c.set(year,c.get(Calendar.MONTH),1);
//获取第一天对应星期几
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
//日历头
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
//将第一天之前用\t空出距离,保证第一天在相应的星期几位置下显示
for(int i=1;i<dayOfWeek;i++){
System.out.print("\t");
}
//循环输出该月所有的天数,7天一循环
for(int i=1;i<=day;i++){
System.out.print(i);
if(dayOfWeek%7==0){
System.out.print("\n");
}else{
System.out.print("\t");
}
dayOfWeek++;
}
}
//获取指定月份的日历,具体方法同 getCurrentCalendar()
public static void getCalendar(int year,int month){
System.out.println(year+"年"+month+"月");
if(month!=12){
c.set(year,month,1);
}else{
c.set(year,0,1);
}
c.add(Calendar.DAY_OF_MONTH,-1);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
c.set(year,month,1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for(int i=1;i<dayOfWeek;i++){
System.out.print("\t");
}
for(int i=1;i<=day;i++){
System.out.print(i);
if(dayOfWeek%7==0){
System.out.print("\n");
}else{
System.out.print("\t");
}
dayOfWeek++;
}
}
//测试
public static void main(String[] args) {
getCurrentDate();
getCurrentCalendar();
getCalendar(2014,4);
}
}