java关于日期的运算等处理方法
2008-01-05 19:13:06 来源:WEB开发网核心提示:jsp中的日期问题及其它:D :D :D/*** @author imagebear*/日期问题1、获取服务器端当前日期:<%@ page import="java.util.Date"%><% Date myDate = new Date();%>2、获取当前年、月、日:&
jsp中的日期问题及其它:D :D :D
/**
* @author imagebear
*/
日期问题
1、获取服务器端当前日期:
<%@ page import="java.util.Date"%><% Date myDate = new Date();%>
2、获取当前年、月、日:
<%@ page import="java.util.Date"%><% Date myDate = new Date(); int thisYear = myDate.getYear() + 1900;//thisYear = 2003 int thisMonth = myDate.getMonth() + 1;//thisMonth = 5 int thisDate = myDate.getDate();//thisDate = 30%>
3、按本地时区输出当前日期
<%@ page import="java.util.Date"%><% Date myDate = new Date(); out.PRintln(myDate.toLocaleString());%>
输出结果为:
2003-5-30
4、获取数据库中字段名为”publish_time“、类型为Datetime的值
<%@ page import="java.util.Date"%><% ...连接数据库... ResultSet rs = ... Date sDate = rs.getDate("publish_time");%>[code]5、按照指定格式打印日期[code]<%@ page import="java.util.Date"%><%@ page import="java.text.DateFormat"%><% Date dNow = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); out.println("It is " + formatter.format(dNow));%>
输出的结果为:
It is 星期五 2003.05.30 at 11:30:46 上午 CST
(更为详尽的格式符号请参看SimpleDateFormat类)
6、将字符串转换为日期
<%@ page import="java.util.Date"%><%@ page import="java.text.DateFormat"%><% String input = "1222-11-11"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date t = null; try{ t = formatter.parse(input); out.println(t); }catch(ParseException e){ out.println("unparseable using " + formatter); }%>
输出结果为:
Fri Nov 11 00:00:00 CST 1222
7、计算日期之间的间隔
<%@ page import="java.util.Date"%><%@ page import="java.text.DateFormat"%><% String input = "2003-05-01"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = null; try{ d1 = formatter.parse(input); }catch(ParseException e){ out.println("unparseable using " + formatter); } Date d2 = new Date(); long diff = d2.getTime() - d1.getTime(); out.println("Difference is " + (diff/(1000*60*60*24)) + " days.");%>
输出结果为:
Difference is 29 days.
8、日期的加减运算
方法:用Calendar类的add()方法
<%@ page import="java.util.*"%><%@ page import="java.text.*"%><% Calendar now = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); out.println("It is now " + formatter.format(now.getTime())); now.add(Calendar.DAY_OF_YEAR,-(365*2)); out.println("<br>"); out.println("Two years ago was " + formatter.format(now.getTime()));%>
[]
赞助商链接