java常用类-java日期处理类
Date类
Date类是jdk给我们提高的标准日期类,在java.util包下;
示例代码:
import java.util.Date; public class TestDate { public static void main(String[] args) { Date date=new Date(); System.out.println("当前日期:"+date); } }
运行发现 格式不符合中国人的习惯。
Calendar类
Calendar是日历类(java.util包),能获取到年月日时分秒的具体值;
public class TestCalendar { public static void main(String[] args) { Calendar calendar=Calendar.getInstance(); System.out.println(calendar.get(Calendar.YEAR)); System.out.println(calendar.get(Calendar.MONTH)+1); // 月份从0开始 要+1 System.out.println("现在是:"+calendar.get(Calendar.YEAR)+"年" +(calendar.get(Calendar.MONTH)+1)+"月" +calendar.get(Calendar.DAY_OF_MONTH)+"日" +calendar.get(Calendar.HOUR_OF_DAY)+"时" +calendar.get(Calendar.MINUTE)+"分" +calendar.get(Calendar.SECOND)+"秒"); } }
SimpleDateFormat类
SimpleDateFormat类(java.text包)主要是用作日期类型转换用的。
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TestSimpleDateFormat { public static String formatDate(Date date,String format){ String result=""; SimpleDateFormat sdf=new SimpleDateFormat(format); if(date!=null){ result=sdf.format(date); } return result; } public static Date formatDate(String dateStr,String format) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat(format); return sdf.parse(dateStr); } public static void main(String[] args) throws ParseException { Date date=new Date(); System.out.println(formatDate(date,"yyyy-MM-dd")); System.out.println(formatDate(date,"yyyy-MM-dd HH:mm:ss")); System.out.println(formatDate(date,"yyyy年MM月dd日HH时mm分ss秒")); String dataStr="1989-11-02 18:01:41"; Date date2=formatDate(dataStr,"yyyy-MM-dd HH:mm:ss"); System.out.println(formatDate(date2,"yyyy-MM-dd HH:mm:ss")); } }
对知识点的补充
补充: 获取今天是星期几
import java.util.Calendar; public class Test { public static void main(String[] args) { String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; Calendar calendar=Calendar.getInstance(); System.out.println("今天是"+weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1]); } }