在Java程序中,针对Java.util.date、Java.util.calendar和Java.text.dateformat
在jdk的有提供两个构造方法,
一个是无参数的构造方法Date()
另一个是接受long的型的参数date的构造方法。用于创建指定时间的date参数的。
calendar类的用于完成日期和时间段的操作。
一般我们要先操作一个calendar的对象,
calendar calendar = calendar.getinstance();
利用这个对象进行获取需要的年月日等其他的时间的字段
方法有
int get(int field); 返回指定的日历的字段
void add (int field ,int amount) 根据念日历的字段的增加或减去指定时间
要注意的月份的获取需要加1,却始值是从0开始不是1开始来着。
void set(int field,int value)值,
void set(int year,int month, int date) 设置calendar对象的年、月、日三个字段。
2、dateformat 类
date的对象,我们需要表示的日期以指定的格式输出的,例如我们的中文的格式时间就要用到dateformat类。
date的抽象类,不能直接实例化,但它通过了静态的方法,通过这些方法可以获取dateformat类的实例对象。并调用了其他相应的方法进行操作。
dateformat 类专门是用于将日期格式化为字符串或者用特定格式显示的日期字符串转换成一个date对象。
package com.hanshu.text;
import java.text.DateFormat;
import java.util.Date;
public class date {
public static void main(String[] args) {
// dateformat 类的一些例子
Date date = new Date();
//full格式的日期格式的对象
DateFormat fullformat = DateFormat.getDateInstance(DateFormat.FULL);
//long格式的日期式的对象
DateFormat longformat = DateFormat.getDateInstance(DateFormat.LONG);
//medium的日期式的对象
DateFormat mediumformat = DateFormat.getDateInstance(DateFormat.MEDIUM);
//shor格式的日期的或时间格式的器的对象
DateFormat shorformat = DateFormat.getDateInstance(DateFormat.SHORT);
//下面打印格式化后的日期或日期时间
System.out.println("当前日期的完整性格式为:"+fullformat.format(date));
System.out.println("当前日期的长格式为"+longformat.format(date));
System.out.println("当前日期的普通格式为"+mediumformat.format(date));
System.out.println("当前日期的短格式为"+shorformat.format(date));
}
}
3、simpledateformat类
在使用dateformat对象将字符串解析为日期时,需要输入固定格式的字符串,这显然不够灵活,
jdk中提供了一个simpledateformat类的,该类是dateformat的子类,simpledateformat类可以使用new关键字创建实例对象,他的构造方法接受一个格式字符参数,表示日期格式模板。
package com.hanshu.text;
import java.text.SimpleDateFormat;
import java.util.Date;
public class date {
public static void main(String[] args) {
//创建一个simpledateformat对象
SimpleDateFormat df1 = new SimpleDateFormat("Gyyyy年mm月dd日:今天是yyyy年的第D天,E");
//按simpledateFormat对象的日期模板格式化date对象
System.out.println(df1.format(new Date()));
/* 还有一种可能就是
* 首先定义一个字符串
* string dt ="2018年8月8日"
* 调用parse的方法,传入刚才的dt的对象在方法里面作为参数。
* 然后就是将对应的格式解析成为date的对象的
*
*
* */
}
}