java Date 时间获取、设置、格式化、时间差

现在的时间+3小时用java实现
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		Date now = new Date();
		//取毫秒值
		long time = now.getTime();
		//年(2018 - 1900 = 118)
		int year = now.getYear();
		//月(0~11)
		int month = now.getMonth();
		//日
		int day = now.getDay();
		//时
		int hours = now.getHours();
		//分
		int minutes = now.getMinutes();
		//秒
		int seconds = now.getSeconds();
		
		System.out.println("time = " + time);
		System.out.println("year = " + year);
		System.out.println("month = " + month);
		System.out.println("day = " + day);
		System.out.println("hours = " + hours);
		System.out.println("minutes = " + minutes);
		System.out.println("seconds = " + seconds);
		
		//设置
		now.setHours(now.getHours() + 3);
		System.out.println("hours + 3 = " + now.getHours());
	}

time = 1529661429648
year = 118
month = 5
day = 5
hours = 17
minutes = 57
seconds = 9
hours + 3 = 20

时间格式化

	public static void main(String[] args) throws ParseException {
		
		String str = "2018-05-18 18:30:00";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = format.parse(str);
		System.out.println(date);
		
		//Fri May 18 18:30:00 CST 2018
	}

计算2个日期相差的天/时/分/秒

public static String getTimeDifference(Date beginTime, Date endTime) {
		Long between = (beginTime.getTime() - endTime.getTime()) / 1000;// 除以1000是为了转换成秒


		String day = ((Long) (between / (24 * 3600))).toString();
		String hour = ((Long) (between % (24 * 3600) / 3600)).toString();
		String minute = ((Long) (between % 3600 / 60)).toString();
		String second = ((Long) (between % 60 / 60)).toString();


		if (hour.length() == 1) {
			hour = "0" + hour.toString();
		}
		if (minute.length() == 1) {
			minute = "0" + minute.toString();
		}
		if (second.length() == 1) {
			second = "0" + second.toString();
		}
		if (day.equals("0")) {
			return hour + ":" + minute + ":" + second;
		} else {
			return day + "天  " + hour + ":" + minute + ":" + second;
		}
	}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值