您的位置:首页 > 编程语言 > Java开发

Json下日期格式控制 与 Java 日期计算

2010-09-15 14:49 519 查看
创建一个日期对象

使用系统的当前日期和时间创建一个日期对象并返回一个长整数的简单例子。这个时间通常被称为Java虚拟机(JVM)主机环境的系统时间。

importjava.util.Date;
publicclassDateExample1{publicstaticvoidmain(String[]args){
//Getthesystemdate/timeDatedate=newDate();System.out.println(date.getTime());}}

今天是星期一,2005年8月8日,上午8:43,上面的例子在系统输出设备上显示的结果是1123461832312。

日期数据的定制格式

使用类java.text.SimpleDateFormat和它的抽象基类java.text.DateFormat完成日期数据的格式定制,比方今天星期一-八月-08-2005。
下面的例子展示了如何完成这个工作:

importjava.text.SimpleDateFormat;importjava.util.Date;
publicclassDateExample2{
publicstaticvoidmain(String[]args){SimpleDateFormatbartDateFormat=newSimpleDateFormat
("EEEE-MMMM-dd-yyyy");Datedate=newDate();System.out.println(bartDateFormat.format(date));}}

只要通过向SimpleDateFormat的构造函数传递格式字符串"EEE-MMMM-dd-yyyy",就能够指明自己想要的格式。运行结果就是:星期一-八月-08-2005了。
传递"EE-MM-dd-yy"会显示星期一-08-08-05。

将文本数据解析成日期对象

假设一个文本字符串包含了一个格式化了的日期对象,而需要解析这个字符串并从文本日期数据创建一个日期对象。下面的例子,
将解析文本字符串"8-8-2005"并创建一个值为1123430400000的日期对象。

例子程序:

importjava.text.SimpleDateFormat;importjava.util.Date;
publicclassDateExample3{
publicstaticvoidmain(String[]args){
//CreateadateformatterthatcanparsedatesoftheformMM-dd-yyyy.
SimpleDateFormatbartDateFormat=newSimpleDateFormat("MM-dd-yyyy");
//Createastringcontainingatextdatetobeparsed.StringdateStringToParse="8-8-2005";
try{//Parsethetextversionofthedate.
//Wehavetoperformtheparsemethodina
//try-catchconstructincasedateStringToParse
//doesnotcontainadateintheformatweareexpecting.
Datedate=bartDateFormat.parse(dateStringToParse);
//Nowsendtheparseddateasalongvalue
//tothesystemoutput.System.out.println(date.getTime());}catch(Exceptionex){
System.out.println(ex.getMessage());}}}

使用标准的日期格式化过程

可以生成和解析定制的日期格式后,现在来看一看如何使用内建的格式化过程。使用方法DateFormat.getDateTimeInstance()可以得到用几种不同的方法
获得标准的日期格式化过程。在下面的例子中,我们获取了四个内建的日期格式化过程。它们包括一个短的,中等的,长的,和完整的日期格式。

importjava.text.DateFormat;importjava.util.Date;

publicclassDateExample4{publicstaticvoidmain(String[]args){Datedate=newDate();
DateFormatshortDateFormat=DateFormat.getDateTimeInstance
(DateFormat.SHORT,DateFormat.SHORT);DateFormatmediumDateFormat=DateFormat.getDateTimeInstance
(DateFormat.MEDIUM,DateFormat.MEDIUM);DateFormatlongDateFormat=DateFormat.getDateTimeInstance
(DateFormat.LONG,DateFormat.LONG);DateFormatfullDateFormat=DateFormat.getDateTimeInstance
DateFormat.FULL,DateFormat.FULL);

System.out.println(shortDateFormat.format(date));
System.out.println(mediumDateFormat.format(date));
System.out.println(longDateFormat.format(date));S
ystem.out.println(fullDateFormat.format(date));}}

注意我们在对getDateTimeInstance的每次调用中都传递了两个值。第一个参数是日期风格,而第二个参数是时间风格。它们都是基本数据类型int(整型)。
考虑到可读性,这里使用了DateFormat类提供的常量:SHORT,MEDIUM,LONG,和FULL。

运行例子程序,它将向标准输出设备输出下面的内容:

05-8-8上午9:17
2005-8-89:17:42
2005年8月8日上午09时17分42秒
2005年8月8日09时17分42秒GMT+08:00

(完成程序测试结果基于JDK1.2.2)

-----------------------------------------------------------------------------------------------------------------------------------

第一个要求很简单的,就是先定制一个年月日字符型格式的日期,然后将它解析成一个日期对象;再设置一个只显示星期几的日期的格式,将上面的日期对象格式输出就行了。

第二个要求也不难,你是想对数据库中的数据操作,我这里就用数组给你模拟一下吧。我定义了两个int变量SHANGBAN,XIUXI,对应你的两个字段值1和0,
然后我对8月的数据进行了操作(我是假设双休日休息,对应今年的这个月),根据输入的年月日字符,用substing提取了各个字段,然后进行相应查找就行了。
你可以用各个字段到数据库中相应的那一天查询对应的值就ok了。

下面是我的程序:

importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.lang.String;
importjava.lang.Integer;
publicclassDateExample{
publicstaticvoidmain(String[]args){
intSHANGBAN=1;//上班
intXIUXI=0;//休息
int[]AugDay={//八月份数据
SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,XIUXI,XIUXI,
SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,XIUXI,XIUXI,
SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,XIUXI,XIUXI,
SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,SHANGBAN,XIUXI,XIUXI,
SHANGBAN,SHANGBAN,SHANGBAN
};
//Createadateformatterthatcanparsedatesoftheformyyyy-MM-dd.
SimpleDateFormatbartDateFormat1=newSimpleDateFormat("yyyy-MM-dd");
//Createastringcontainingatextdatetobeparsed.
StringdateStringToParse="2005-8-10";//可以改成接受输入
try{
Datedate=bartDateFormat1.parse(dateStringToParse);
SimpleDateFormatbartDateFormat2=newSimpleDateFormat("EEEE");
System.out.println(dateStringToParse+""+bartDateFormat2.format(date));

intyear=Integer.parseInt(dateStringToParse.substring(0,4));
intmonth=Integer.parseInt(dateStringToParse.substring(5,6));
intday=Integer.parseInt(dateStringToParse.substring(7,9));

if(month==8){
//假如输入的是8月份的话(这里只是演示,指的是今年8月,你可以按你的需要修改)
if(AugDay[day-1]==SHANGBAN){
System.out.println("今天上班");
}
else{
System.out.println("今天休息");
}
}
}
catch(Exceptionex){
System.out.println(ex.getMessage());
}
}
}

输入时间是2005-8-10,只用了八月的数组里的值来显示大体的意思,你完全可以修改满足你的需要。最后显示结果为:

2005-8-10星期三
今天上班

好了,应该很清楚了吧,加油,也感谢你的支持!

ILOVEJAVA!


jstlfmt:formatdate

<%@pagelanguage="java"contentType="text/html;charset=gb18030"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/fmt"prefix="fmt"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<html>
<head>
<title>MyJSP'fmt.jsp'startingpage</title>
</head>

<body>
<c:setvar="salary"value="3540.2301"/>
<c:setvar="total"value="56225.2301"/>
<fmt:setLocalevalue="en_US"/>
currency:<fmt:formatNumbervalue="${salary}"type="currency"currencyCode="USD"/><br>
percent:<fmt:formatNumbervalue="${salary/total}"type="percent"maxFractionDigits="4"/><br>
<hr>
<jsp:useBeanid="now"class="java.util.Date"></jsp:useBean>
<fmt:setLocalevalue="zh_CN"/>
full--><fmt:formatDatevalue="${now}"type="both"dateStyle="full"timeStyle="full"/><br>
long--><fmt:formatDatevalue="${now}"type="both"dateStyle="long"timeStyle="long"/><br>
medium--><fmt:formatDatevalue="${now}"type="both"dateStyle="medium"timeStyle="medium"/><br>
default--><fmt:formatDatevalue="${now}"type="both"dateStyle="default"timeStyle="default"/><br>
short--><fmt:formatDatevalue="${now}"type="both"dateStyle="short"timeStyle="short"/><br>
</body>
</html>
今天是:<fmt:formatDatevalue="${now}"pattern="Gyyyy年MM月dd日E"/><br>
现在是:<fmt:formatDatevalue="${now}"pattern="aHH:mm:ss.Sz"/>
结果:
今天是:公元2007年10月19日星期五
现在是:下午20:04:11.484CST

<%@taglibprefix="c"uri="http://java.sun.com/jstl/core"%>
<%@taglibprefix="fmt"uri="http://java.sun.com/jstl/fmt"%>

<fmt:parseDatevalue="${param.date}"var="date"pattern="yyyy/MM/dd:HH:mm:ss>
<fmt:parseDatevalue="${param.isoDate}"var="isoDate"pattern="yyyyMMdd'T'HHmmss">

Theinputparametersmustmatchthepatterns,ortheJSPwillthrownanexception.Thispagedoesnoerrorhandling.

Inputparameters:
Date:2004/04/01:13:30:00Javaformat:ThuApr0113:30:00CST2004
isoDate:20040531T235959Javaformat:MonMay3123:59:59CDT2004

Dates
TagOutput
Attribute:value;required.Taghasnobody.
<fmt:formatDatevalue="${date}"type="both"/>

2004-4-113:30:00
<fmt:formatDatevalue="${isoDate}"type="both"/>

2004-5-3123:59:59
Attribute:type;optional.Indicateswhattoprint:date,time,orboth.
<fmt:formatDatevalue="${date}"type="date"/>

2004-4-1
<fmt:formatDatevalue="${isoDate}"type="time"/>

23:59:59
Attribute:dateStyle;optional.Variesthedateformat.
<fmt:formatDatevalue="${isoDate}"type="date"dateStyle="default"/>

2004-5-31
<fmt:formatDatevalue="${isoDate}"type="date"dateStyle="short"/>

04-5-31
<fmt:formatDatevalue="${isoDate}"type="date"dateStyle="medium"/>

2004-5-31
<fmt:formatDatevalue="${isoDate}"type="date"dateStyle="long"/>

2004年5月31日
<fmt:formatDatevalue="${isoDate}"type="date"dateStyle="full"/>

2004年5月31日星期一
Attribute:timeStyle;optional.Variesthetimeformat.
<fmt:formatDatevalue="${isoDate}"type="time"timeStyle="default"/>

23:59:59
<fmt:formatDatevalue="${isoDate}"type="time"timeStyle="short"/>

下午11:59
<fmt:formatDatevalue="${isoDate}"type="time"timeStyle="medium"/>

23:59:59
<fmt:formatDatevalue="${isoDate}"type="time"timeStyle="long"/>

下午11时59分59秒
<fmt:formatDatevalue="${isoDate}"type="time"timeStyle="full"/>

下午11时59分59秒CDT
Attribute:pattern;optional.Inidcatesdate/timecustompatterns.
<fmt:formatDatevalue="${date}"type="both"pattern="EEEE,MMMMd,yyyyHH:mm:ssZ"/>

星期四,四月1,200413:30:00-0600
<fmt:formatDatevalue="${isoDate}"type="both"pattern="dMMMyy,h:m:sazzzz/>

31五月04,11:59:59下午中央夏令时


==========================================================================

Java日期计算收藏

Java中提供了丰富的日期表示方式。其中包括Date、Timestamp、Calendar、GregorianCalendar类。GregorianCalendar类中提供了用于计算日期的add()方法,
可以很方便地计算若干年、月、日后的日期。

给个例子看看:

packagetestjava;

importjava.sql.Timestamp;

importjava.text.SimpleDateFormat;

importjava.util.Date;

importjava.util.GregorianCalendar;

publicclassDateTest{

publicstaticvoidmain(String[]args){

SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-dd");

DateTesttest=newDateTest();

//Date

DatecurrentDate=newDate();

System.out.println("当前日期是:"+df.format(currentDate));

System.out.println("一周后的日期是:"+df.format(test.nextWeek(currentDate)));

System.out.println("一月后的日期是:"+df.format(test.nextMonth(currentDate)));

System.out.println("一年后的日期是:"+df.format(test.nextYear(currentDate)));

//Timestamp

TimestampcurrentTime=newTimestamp(System.currentTimeMillis());

System.out.println("当前日期是:"+df.format(currentTime));

System.out.println("一周后的日期是:"+df.format(test.nextWeek(currentTime)));

System.out.println("一月后的日期是:"+df.format(test.nextMonth(currentTime)));

System.out.println("一年后的日期是:"+df.format(test.nextYear(currentTime)));

//另一种计算方式,这种方式计算月和年的日期比较困难

TimestampnextTime=newTimestamp(currentTime.getTime()+7*24*60*60*1000);

System.out.println("当前日期是:"+df.format(currentTime));

System.out.println("一周后的日期是:"+df.format(nextTime));

}

//获取下一周的日期

publicDatenextWeek(DatecurrentDate){

GregorianCalendarcal=newGregorianCalendar();

cal.setTime(currentDate);

cal.add(GregorianCalendar.DATE,7);//在日期上加7天

returncal.getTime();

}

//获取本周日的日期

publicDategetSunday(Datemonday){

GregorianCalendarcal=newGregorianCalendar();

cal.setTime(monday);

cal.add(GregorianCalendar.DATE,6);//在日期上加6天

returncal.getTime();

}

//获取下一月的日期

publicDatenextMonth(DatecurrentDate){

GregorianCalendarcal=newGregorianCalendar();

cal.setTime(currentDate);

cal.add(GregorianCalendar.MONTH,1);//在月份上加1

returncal.getTime();

}

//获取下一年的日期

publicDatenextYear(DatecurrentDate){

GregorianCalendarcal=newGregorianCalendar();

cal.setTime(currentDate);

cal.add(GregorianCalendar.YEAR,1);//在年上加1

returncal.getTime();

}

}


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: