java语言显示运算时间_对Java语言中的日期处理大全

1、获取服务器端当前日期:

Date myDate = new Date();

%>

2、获取当前年、月、日:

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、按本地时区输出当前日期

Date myDate = new Date();

out.println(myDate.toLocaleString());

%>

输出结果为:

2003-5-30

4、获取数据库中字段名为"publish_time"、类型为Datetime的值

...连接数据库...

ResultSet rs = ...

Date sDate = rs.getDate("publish_time");

%>

5、按照指定格式打印日期

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、将字符串转换为日期

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、日期的加减运算

方法:用Calendar类的add()方法

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("
");

out.println("Two years ago was " +

formatter.format(now.getTime()));

%>

输出结果为:

It is now 星期五 2003.05.30 at 01:45:32 下午 CST

Two years ago was 星期三 2001.05.30 at 01:45:32 下午 CST

8、比较日期

方法:用equals()、before()、after()方法

DateFormat df = new SimpleDateFormat("yyy-MM-dd");

Date d1 = df.parse("2000-01-01");

Date d2 = df.parse("1999-12-31");

String relation = null;

if(d1.equals(d2))

relation = "the same date as";

else if(d1.before(d2))

relation = "before";

else

relation = "after";

out.println(d1 +" is " + relation + + d2);

%>

输出结果为:

Sat Jan 01 00:00:00 CST 2000 is after Fri Dec 31 00:00:00 CST

1999

9、记录一件事所花费的时间

方法:调用两次System.getTimeMillis()方法,求差值

long t0,t1;

t0 = System.currentTimeMillis();

out.println("Cyc starts at " + t0);

int k = 0;

for(int i =0;i<100000;i++)

t1 = System.currentTimeMillis();

out.println("
");

out.println("Cyc ends at " + t1);

out.println("
");

out.println("This run took " + (t1-t0) + "ms.");

%>

输出结果为:

Cyc starts at 1054275312432

Cyc ends at 1054275312442

This run took 10ms.

10:如何格式化小数

DecimalFormat df = new DecimalFormat(",###.00");

double aNumber = 33665448856.6568975;

String result = df.format(aNumber);

out.println(result);

%>

输出结果为:

33,665,448,856.66

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值