gpt4 book ai didi

java - java中将时间戳转换为特定格式(年、月、周、日、时、时、分、秒)

转载 作者:行者123 更新时间:2023-12-01 23:11:03 29 4
gpt4 key购买 nike

这是我的代码,

例如2年2个月1周2天1小时2分35秒。

    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 = new Date();
Date d2 = new Date();
long year =(1000*60*60*24*365l);
long month =(1000*60*60*24*30l);
long weeks =(1000*60*60*24*7l);
long days =(1000*60*60*24l);

try{

d1 = df.parse(stdate);
d2 = df.parse(endate);
long diff = d2.getTime()-d1.getTime();
long diffYear = diff/(1000*60*60*24*365l);
long diffMonth = (diff-(diffYear*year))/month;
long diffWeeks = ((diff%month))/weeks;
long diffDays = ((diff%weeks))/days;

System.out.println(diffYear+" years ");
System.out.println(diffMonth+" months ");
System.out.println(diffWeeks+" week ");
System.out.println(diffDays+" days "); // wrong output,
}catch(Exception e){

}

o/p:

1年
10个月
2周
5天

我不想使用 joda 时间。它应该在 java.util.*;

请回答,先谢谢了。

最佳答案

您可以尝试使用Period来自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
<小时/>

更新:

回答你原来的问题:就像你减去已经属于 year 的天数一样。来自diff要计算月份,您需要减去

  • year 使用的天数总和和month计算weeks
  • 如果要计算,则已属于年、月、周的天数总和 days

所以你的代码看起来像

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 .

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

  • 更改lL因为l看起来像 1所以这可能会令人困惑,
  • 开始乘以long .

为了让事情变得更容易,你甚至可以将其写为

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;

关于java - java中将时间戳转换为特定格式(年、月、周、日、时、时、分、秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967785/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com