且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将时间戳转换为java中的特定格式(年,月,周,日,时间,小时,分钟和秒)

更新时间:2022-11-13 15:10:22

您可以尝试使用期间 Joda-time

String stdate = "01/01/2014 09:30:30";
String endate = "09/11/2015 11:30:30";
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date d1 = df.parse(stdate);
Date d2 = df.parse(endate);;

DateTime startTime = new DateTime(d1), endTime = new DateTime(d2);
Period p = new Period(startTime, endTime);
System.out.printf("%-8s %d %n","years:",p.getYears());
System.out.printf("%-8s %d %n","months:",p.getMonths());
System.out.printf("%-8s %d %n","weeks:",p.getWeeks());
System.out.printf("%-8s %d %n","days:",p.getDays());
System.out.printf("%-8s %d %n","hours:",p.getHours());
System.out.printf("%-8s %d %n","minutes:",p.getMinutes());
System.out.printf("%-8s %d %n","second:",p.getSeconds());

输出:

years:   1 
months:  10 
weeks:   1 
days:    1 
hours:   2 
minutes: 0 
second:  0 






更新:


Update:

回答您的原始问题:就像您从 diff $ c $中减去已经属于年的日期 c>计算月份,您需要减去

To answer your original question: Just like you are subtracting days that already belongs to year from diff to calculate months, you need to subtract


  • 年使用的天数总和月份来计算

  • 已经属于年,月,周如果要计算

  • sum of days used on year and month to calculate weeks
  • sum of days which already belong to year, month, week if you want to calculate days

所以你的代码可以看起来像

so your code can look like

long diffYear = diff / year;
long diffMonth = (diff - (diffYear * year)) / month;
//long diffWeeks= ((diff % month)) / weeks;
long diffWeeks = (diff - (diffYear * year + diffMonth * month)) / weeks;
//long diffDays = ((diff % weeks)) / days;
long diffDays = (diff - (diffYear * year + diffMonth * month + diffWeeks*weeks)) / days;//((diff % weeks)) / days;

警告:这种计算日或周的方式将会将每个月视为30天,这并不总是真的,因为也可以有28,29,30,31天的月份。这就是为什么而不是 1 日,你会看到 5

WARNING: This way of calculating days or weeks will treat each month as 30 days, which is not always true, because there can be also 28,29,30,31 day months. That is why instead of 1 day you will see 5.

警告2 :而不是 1000 * 60 * 60 * 24 * 365l 对于较大的数字可能会导致整数溢出(使用的第一个数字整数),您应该使用 1000L * 60 * 60 * 24 * 365 。所以

WARNING 2: Instead of 1000*60*60*24*365l which for larger numbers can cause integer overflow (first numbers used are integers) you should use 1000L*60*60*24*365. So


  • 更改 l L 因为 l 看起来像 1 ,所以可能会令人困惑,

  • 开始乘以 long

  • change l to L because l looks like 1 so it can be confusing,
  • start multiplying with long.

为了使事情变得更容易,你甚至可以写它作为

To make things easier you can even write it as

long seconds = 1000L;
long minutes = seconds * 60;
long hours = minutes * 60;
long days = hours * 24;
long weeks = days * 7;
long month = days * 30;
long year = days * 365;