- ·上一篇文章:【JAVA基础知识】第八章 常用使用类(4)
- ·下一篇文章:【JAVA基础知识】第八章 常用实用类(2)
【JAVA】基础知识 第八章 常用实用类(3)
[t]8.4 Date与Calendar类[/t]
[t]Date类[/t]
1.使用无参数构造方法
使用Date类的无参数构造方法创建的对象可以获取本机的当前日期和时间。
1 | Date nowTime=new Date(); |
那么,当前nowTime对象中含有的日期和时间就是创建nowTime对象时本地计算机的日期和时间。
2.带参数的构造方法
计算机系统将其自身的时间的“公元”设置在1970年1月1日0时(格林威治时间),可以根据这个时间使用Date的带参数的构造方法Date(long time)来创建一个Date对象,例如:
1 2 3 | Date date1=new Date(1000), date2=new Date(-1000); |
其中的参数取正表示公元后的时间,取负数表示公元前的时间。
[t]8.4.2 ?Calendar 类[/t]
Calendar类在java.util包中,使用Calendar类的static方法getInstance()可以初始化一个日历对象,如:
Calendar calendar=Calendar.getInstance();
然后,calendar对象可以调用方法:
1 2 3 4 5 | public final void set(int year,int month,int data) public final void set(int year,int month,int data,int hour,int minute) public final void set(int year,int month,int data,int hour,int minute,int second) |
将日历翻到任何一个时间,当参数year取负数时表示公元前。
calendar对象调用方法 public int get(int field) 可以获取有关年份、月份、小时、星期等信息,参数field的有效值由Calendar的静态常量指定。
1 | calendar.get(Calendar.MONTH); |
返回一个整数,如果是0则表示当前日历的1月。。。以此类推
1 | calendar.get(Calendar.DAY_OF_WEEK); |
返回一个整数,如果该整数是1表示星期日,如果是2,表示星期一
日历调用public long getTimeInMillis()可以将时间表示毫秒。
[t]8.5 日期格式化[/t]
8.5.1 Formatter类的format方法:
format(格式化模式,日期列表)
接着“格式化模式”返回“日期列表”中所列各个日期中所含数据(年,月,日,小时等数据)的字符串表示。我们可以使用String类调用format方法对日期进行格式化。
1. 格式化模式
1 | String s=String.format(“%tY年%tm月%td日”,new Date(),new Date(),new Date()); |
2. 日期列表
3. 格式化同一日期
1 | String s=String.format("%tY年%<tm月%<td日",new Date()); |
4. 常用的日期格式符及作用
>%tY 格式化“年”格式化为4位形式,例如2015
%ty 格式化“年”为2位形式 15
%tm 格式化“月”为2位形式,(01~13)
%tp 格式化“日”为当前环境下的上午或者下午。
%td 格式化“日”(为当前月的第几天)(01~31)
%tj 格式化“日”为当前年的第几天(0001~365)
%tB 格式化“月”为月份的全称(一月~12月)
%tb 格式化“月”为月份的简称 (一月~12月)
%tA 格式化“日”为星期几的全称(星期一 ~ 星期日,%ta 同理)
%tH 格式化“时”为24小时制,即 00~ 23
%tI 格式化“时”为12小时制(01~12)
%tM 将日期中的“分”格式化位2位形式,即(00~60)
%tS 格式化“秒”为2位形式(00~60)
%tL 格式化“毫秒”为3位形式,(000~999)
%tN 格式化“微妙” 为9位形式,即(000000000~999999999)
%tR 等价于 %tH:%tM
%tT 等价于 %tH:%tM:%tS
%tr 等价于 %tI:%tM:%tS%Tp
%tD 等价于 %tm/%td/%ty
%tF 等价于 %tY-%tm-%td
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.format; import java.util.Calendar; import java.util.Formatter; import java.util.Date; public class example { public static void main(String[] args) { Date date=new Date(); System.out.println(date); String s="%tY-%<tm-%<td %<tA(%<tp) %<tT"; String time=String.format(s, date); System.out.println(time); Calendar calendar=Calendar.getInstance(); calendar.set(2022,11,31,07,19,45); String s1=String.format("%tY年%<tb%<td日(%<tT)", calendar); System.out.println(s1); } } |
【JAVA】基础知识 第八章 常用实用类(3)