Java基础 时间

来源:互联网 发布:阿里云 华北5 速度 编辑:程序博客网 时间:2024/05/17 01:40
import java.text.DateFormat;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.Date;public class TeseFormat {public static void main(String[] args) throws Exception{//创建一个时间格式化的对象 并且设定格式SimpleDateFormat a=new SimpleDateFormat("yyyy-MM-dd");//创建一个时间对象Date date=new Date();//format将给定的 Date格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。System.out.println(a.format(date));//将按照格式输入时间  转换为对象 返回date=a.parse("2017-05-22");//打印输出System.out.println(date);//创建一个数字型的格式化模式  设置格式化模式DecimalFormat b=new DecimalFormat("##,####.000");System.out.println(b.format(1234214535.2423));//将字符串转为基本数据类型System.out.println(Double.parseDouble("123321.31"));}}

Date类表示特定的瞬间,精确到毫秒。Date类的构造器Date();
Date(long milliSeconds);其他构造方法已经废弃不用
Date类常用方法int getYear(); 年int getMonth(); 月(0-11)int getDate(); 日(1-31)
Date类常用方法
int getDay(); 星期int getHours(); 时int getMinutes(); 分int getSeconds(); 秒long

getTime(); 获取当前时间的毫秒数void set…(int value) 设置年月日时分秒boolean after

(Date d); 比较日期大小

Calendar及子类Calendar类java.util.Date类中获取当前年、月、日和将时间格式化以及将字符串

类型的日期转换为Date对象的方法都已经被废弃。如果想要获取Date对象的年、月、日、星期等操

作,需要使用Calendar类以及其子类完成。Calendar是一个抽象类,它为获取和修改年、月、日、

星期等日历字段提供了一系列的方法。Calendar getInstance(); 返回一个Calendar对象int get

(int field); 返回给定日历字段的值void set(int field,int value); 将给定的日历字段设置为

给定值
Calendar类常用方法Date getTime(); 将Calendar对象转换为Date对象Calendar setTime(Date

d); 将Date对象转换为 日历对象int getActualMaximum(int field); ;返回指定日历字段可能拥

有的最大值long getTimeInMillis(); 返回当前时间的毫秒数String toString(); 将Calendar转

换为字符串
Calendar类常用属性
int YEAR 年
int MONTH 月(0-11)
Calendar及子类Calendar类常用属性int DAY_OF_MONTH 日(0-31)int DAY_OF_WEEK 星期(1-7)int

HOUR小时(0-11)int HOUR_OF_DAY(0-23)int MINUTEint SECOND int MILLISECOND毫秒int

DAY_OF_YEAR今年的第几天Calendar及子类GregorianCalendar类GregorianCalendar是Calendar的

一个直接子类,提供了世界上大多数国家/地区使用的标准日历系统,即中国所谓的阳历或者公历


GregorianCalendar的构造器GregorianCalendar()
GregorianCalendar(int year,int month,int day)
GregorianCalendar类常用方法
boolean isLeapYear(int year); 是否为闰年Format的子类

java.text包下的格式化类Format的子类提供以与自然语言无关的方式来处理文本、日期、数字和
消息的类和接口DateFormat以及子类SimpleDateFormatNumberFormat以及子类
DecimalFormatDateFormat是一个抽象的时间格式化类,在格式化和解析日期时间过程中,
其子类

SimpleDateFormat更为常用NumberFormat是一个数字格式化抽象类,通常情况下会使用其子类

DecimalFormat格式化或者解析数字
Format的子类SimpleDateFormat类SimpleDateFormat的
构造器SimpleDateFormat(String pattern);
按照指定的模式创建SimpleDateFormat对象SimpleDateFormat常用方法
SimpleDateFormat常用方法
Date parse(String str); 将String 解析为 DateDecimalFormat类
DecimalFormat是NumberFormat的一个具体子类,用于格式化十进制数字。该类设计有各种功能,
使其能够解析和格式化任意语言环境中的数,包括对西方语言、阿拉伯语和印度语数字的支持。
DecimalFormat的构造器DecimalFormat(String pattern);
按照指定的模式创建DecimalFormat对象DecimalFormat
常用方法
String format(double d); 将double 格式化为 StringNumber parse

(String str); 将String 解析为 Number