晨魅--时间处理方法

来源:互联网 发布:即时通讯软件下载 编辑:程序博客网 时间:2024/05/17 21:57

1        时间格式转换

java.text.SimpleDateFormat是DateFormat的直接子类,java.text.DateFormat是抽象类,DateFormat是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并分析日期或时间,SimpleDateFormat 是一个以与语言环境相关的方式来格式化和分析日期的具体类。

时间格式:yyyy-MM-ddHH:mm:ss,y:年,M:月,d:日 H:小时,m:分,s:秒。注意月是大写的M,分是小写的m。

1.1    String类型转Date类型

Stringtime = “2017-2-14”;

SimpleDateFormatsdf = new SimpleDateFormat(yyyy-MM-dd);

Datedate = sdf.parse(time);

代码实际应用样例:

String getTime = drawNumJson.getString("time");

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Date date = sdf.parse(getTime);

1.2    Date类型转String类型

Datedate=new Date();;

SimpleDateFormatsdf = new SimpleDateFormat(yyyy-MM-dd);

Stringtime = sdf.format (date);

代码实际应用样例:

Date newTime = new Date();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

String voteNewTime = formatter.format(newTime);

1.3    标准时间格式“Fri Jan 13 2017 08:00:00 GMT+0800 (中国标准时间)”的转换

有时传过来的时间格式是“FriJan 13 2017 08:00:00 GMT+0800 (中国标准时间)”这样的字符串,这时我们需要对他进行转换,转换成正常的Date类型格式。

代码实际应用样例:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

String appointmentDate = formatter.format(new Date(date));

1.4    SQL时间格式转换(MySQL)

DATE_FORMAT() 函数用于以不同的格式显示日期/时间数据。

语法:DATE_FORMAT(date,format)。

date:参数是合法的日期。format:规定日期/时间的输出格式。

常用格式有:

格式

描述

%Y

年,4位

%m

月,数值(1-12)

%d

天,数值(00-31)

%e

天,数值(0-31)

%H

小时(00-23)

%i

分钟,数值(00-59)

%S

秒(00-59)

%s

秒(00-59

代码实际应用样例:

select date_format(car_time,'%y-%m-%d %H:%i') as car_time

form cli_app_rel

2        时间的获取

2.1    获取当前时间

Date date=new Date();

代码实际应用样例:

Date newTime = new Date();

 

2.2    获取昨天,今天和明天

public static void main(String[] args) {

               SimpleDateFormat df=newSimpleDateFormat("yyyy-MM-dd");

               Calendarcalendar=Calendar.getInstance();

               calendar.roll(Calendar.DAY_OF_YEAR,-1);

               System.out.println("昨天:"+df.format(calendar.getTime()));

               calendar=Calendar.getInstance();             

               System.out.println("今天:"+df.format(calendar.getTime()));

               calendar.roll(Calendar.DAY_OF_YEAR,1);

               System.out.println("明天:"+df.format(calendar.getTime()));

           }

求明天的代码实际应用样例(昨天,今天用法相同):

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();

calendar.roll(Calendar.DAY_OF_YEAR,1);

String carDate = df.format(calendar.getTime());

3        时间大小比较

假设定义Date a 和 Date b,并且实例化了a 和b.

a.after(b)返回一个boolean,如果a的时间在b之后(不包括等于)返回true。

b.before(a)返回一个boolean,如果b的时间在a之前(不包括等于)返回true。

a.equals(b)返回一个boolean,如果a的时间和b相等返回true。

判断a的时间在b之后的代码实际应用样例(其它用法相同):

Date nowTime = new Date();

if(date.after(nowTime)){

方法体;

}

晨魅

1 0
原创粉丝点击