Date Difference

本文演示如何使用Java中的Calendar类计算两个日期之间的毫秒差,并将其转换为秒、分钟、小时和天数。
This example learns how to make the difference between two dates and how to convert milliseconds into seconds, seconds into minutes, minutes into hours, hours into days.

Here we are using Calendar, an abstract base class that extends Object class and makes a difference between a Date object and a set of integer fields. Calendar class provides a getInstance() method for returning a Calendar object whose time fields have been initialized with the current date and time.

The methods used:
setTimeInMillis(long millis): This method is used to set current time in calendar object.

getInstance(): This method is used to get a calendar using the default time zone, locale and current time.

The code of the program is given below:

package com.test.day10.date;

import java.util.Calendar;

import org.junit.Test;

/**
 * @author BigBird
 * @date 2011-12-11 下午05:19:03
 * @action 测试时间差
 */
public class TimeDifferenceTest {

	@Test
	public void test1() {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.set(2011, 12, 10, 9, 00, 00);
		calendar2.set(2011, 12, 11, 17, 51, 11);
		long millisecond1 = calendar1.getTimeInMillis();
		long millisecond2 = calendar2.getTimeInMillis();
		long diff = millisecond2 - millisecond1;
		long diffSeconds = diff / 1000;
		long diffMinutes = diff / (60 * 1000);
		long diffHours = diff / (60 * 60 * 1000);
		long diffDays = diff / (24 * 60 * 60 * 1000);
		System.out.println("\nThe Date Different Example");
		System.out.println("Time in milliseconds: " + diff + " milliseconds.");
		System.out.println("Time in seconds: " + diffSeconds + " seconds.");
		System.out.println("Time in minutes: " + diffMinutes + " minutes.");
		System.out.println("Time in hours: " + diffHours + " hours.");
		System.out.println("Time in days: " + diffDays + " days.");
	}
}

The output of the program is given below:

The Date Different Example
Time in milliseconds: 118271000 milliseconds.
Time in seconds: 118271 seconds.
Time in minutes: 1971 minutes.
Time in hours: 32 hours.
Time in days: 1 days.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值