这个程序告诉我哪个时间是开始日期和结束,现在我问你是否要在s
(是)添加起始期间时输入另一个时期,但是这个想要加入以上,例如,我添加以下内容:
16/08/1993 - 09/09/2014 = 21年,0个月,24天。
14/02/1995 - 18/05/2001 = 6年,3个月,35天
总计:................................. 27年3个月59天
注意:我不知道是否有问题并尝试一切。我是java新手。
public void diferencia(){
char seguir=0;
Scanner teclado =new Scanner(System.in);
do{
System.out.println("day/Month/year ");
System.out.println("Write the first date: ");
String dayini = teclado.next();
System.out.println("write the second date: ");
String dateactual = teclado.next();
String[] aFechaIng = dateini.split("/");
Integer dayini = Integer.parseInt(aFechaIng[0]);
Integer monthini = Integer.parseInt(aFechaIng[1]);
Integer yearini = Integer.parseInt(aFechaIng[2]);
String[] aFecha = dateactual.split("/");
Integer dayactual= Integer.parseInt(aFecha[0]);
Integer monthactual = Integer.parseInt(aFecha[1]);
Integer yearactual = Integer.parseInt(aFecha[2]);
int b = 0;
int days = 0; //DAYS
int month = 0; //MONTH
int years = 0; //YEARS
int months = 0; //MONTHS
month = monthini - 1;
// LEAP YEAR
if(month==2){
if ((yearactual % 4 == 0) && ((yearactual % 100 != 0) || (yearactual % 400 == 0))){
b = 29;
}else{
b = 28;
}
}else if(month <= 7){
if(month == 0){
b = 31;
}else if(month % 2==0){
b = 30;
}else{
b = 31;
}
}else if(month > 7){
if(month % 2 == 0){
b = 31;
}else{
b = 30;
}
}
if((yearini > yearactual) || (yearini == yearactual && monthini > monthactual) ||
(yearini == yearactual && monthini == monthactual && dayini > dayactual)){
// errors
System.out.println("The start date must be minor ");
}else{ //time periods
if(monthini <= monthactual){
years = yearactual - yearini;
if (dayini <= dayactual){
mmonths = monthactual - monthini;
days = b - (dayini - dayactual);
}else{
if(monthactual == monthini){
years = years - 1;
}
months = (monthactual - monthini - 1 + 12) % 12;
days = b - (dayini - dayactual);
}
}else{
years = yearactual - yearini - 1;
//System.out.println("Años?¿: " + anios);
if(dayini > dayactual){
months = monthactual - monthsini - 1 + 12;
days = b - (dayini - dayactual);
}else{
months = monthactual - monthini + 12;
days = dayactual - dayini;
}
}
}
System.out.println("Years: "+years);
System.out.println("Months: "+months);
System.out.println("Days: "+days);
System.out.println("You want to add another period?? ");
seguir = teclado.next().charAt(0);
}while(seguir!='n');
}//finish method diferencia
答案 0 :(得分:2)
使用joda-time ...
Scanner in = new Scanner(System.in);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String input;
long totalDuration=0;
while (!(input = in.nextLine()).equals("quit")) {
// todo validate input
String[] dates = input.split("-");
Date start = sdf.parse(dates[0].trim());
Date end = sdf.parse(dates[1].trim());
long duration = end.getTime() - start.getTime();
Period period = new Period(0, duration, PeriodType.yearMonthDay());
System.out.println("Duration: " + period.getYears() + "years " + period.getMonths() + "months " + period.getDays() + "days");
totalDuration += duration;
}
Period total = new Period(0, totalDuration, PeriodType.yearMonthDay());
System.out.println("Total duration is: " + total.getYears() + "years " + total.getMonths() + "months " + total.getDays() + "days");
顺便说一下,用英文和格式化代码命名的变量更容易阅读;)
答案 1 :(得分:0)
在开始循环之前,创建三个变量,即totalAnios(totalYears),totalMeses(totalMonths),totalDias(totalDays)并将它们初始化为0.
int totalAnios = 0;
int totalMeses = 0;
int totalDias = 0;
do {
....
}
在关闭循环之前(在while(...)之前),您必须将年,月和日的差异添加到您创建的先前varibales(totalAnios,totalMeses,totalDias)并打印结果。
do {
...
/* your calculation goes here */
totalAnios += anios;
totalMeses += meses;
totalDias += dias;
System.out.println("total : " + totalAnios + " " + totalMeses + " " + totalDias);
} while (seguir != 'n');
每次用户选择留在循环中时,我们将之前的结果相加并打印总数。
顺便说一句,下次不要忘记格式化代码并将变量放在英文中;)。
答案 2 :(得分:0)
你的数学不正确。 14/02/1995 - 18/05/2001 = 6 years, 3 months, 35 days
应为14/02/1995 - 18/05/2001 = 6 years, 3 months, 4 days
。四天,而不是三十五天。
Joda-Time库内置了此功能。无需重新发明轮子。
Java 8中的java.time package可能有类似的东西。这个软件包的灵感来自Joda-Time,但是经过了重新设计。
避免与Java捆绑在一起的java.util.Date和.Calendar类。众所周知,它们很麻烦。 Oracle / Sun决定用新的java.time包取代它们。
您在此处看到的字符串由ISO 8601标准定义,这是生成/解析字符串时Joda-Time和java.time的默认值。
日期时间为YYYY-MM-DDTHH:MM:SS.SSS±HH:MM
。或者,偏移量为Z
,意味着Zulu
时间,意为UTC。
在标准中,Duration
(Joda-Time调用Period
)写成:PnYnMnDTnHnMnS
。 T
将日期部分与时间部分分开。 P
启动每个值。
在评论中,原始海报要求将期间组合归一化。也就是说,调整数字而不是&#34; 7周&#34;我们得到&#34; 1个月,3个星期&#34;。该示例显示了如何执行此操作。请注意,这种正常化假设为12个月,7天,24小时,60分钟和60秒。这种假设可能适合您的业务规则,也可能不适合。
如果要指定其他类型的句点,请使用传递PeriodType
对象。也许你想要几个月和几天没有任何一周。
Joda-Time还提供了一个Duration
类,用于跟踪一对日期时间值之间的精确毫秒数。这可以作为Period
的替代方案,我们将时间跟踪为年,月等大块,而不是精确的经过时间。
您可能想要也可能不想使用时区。如果没有,请使用DateTimeZone.UTC
24小时。
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // or DateTimeZone.UTC
DateTime start_a = new DateTime( "1993-08-16" , timeZone ); // Could call `.withTimeAtStartOfDay()` but that is the default behavior for date-only string.
DateTime stop_a = new DateTime( "2014-09-09" , timeZone );
Interval interval_a = new Interval( start_a , stop_a );
Period period_a = interval_a.toPeriod();
DateTime start_b = new DateTime( "1995-02-14" , timeZone );
DateTime stop_b = new DateTime( "2001-05-18" , timeZone );
Interval interval_b = new Interval( start_b , stop_b );
Period period_b = interval_b.toPeriod();
Period periodCombined = period_a.plus( period_b );
Period periodCombinedNormalized = periodCombined.normalizedStandard(); // Assumes that all years are 12 months, all weeks are 7 days, all days are 24 hours, all hours are 60 minutes and all minutes are 60 seconds. Not true for Daylight Saving Time and other anomalies.
转储到控制台。
System.out.println( "start_a:" + start_a );
System.out.println( "stop_b:" + stop_b );
System.out.println( "interval_a:" + interval_a );
System.out.println( "period_a:" + period_a );
System.out.println( "start_b:" + start_b );
System.out.println( "stop_b:" + stop_b );
System.out.println( "interval_b:" + interval_b );
System.out.println( "period_b:" + period_b );
System.out.println( "periodCombined:" + periodCombined );
System.out.println( "periodCombinedNormalized:" + periodCombinedNormalized );
跑步时。
start_a:1993-08-16T00:00:00.000-04:00
stop_b:2001-05-18T00:00:00.000-04:00
interval_a:1993-08-16T00:00:00.000-04:00/2014-09-09T00:00:00.000-04:00
period_a:P21Y3W3D
start_b:1995-02-14T00:00:00.000-05:00
stop_b:2001-05-18T00:00:00.000-04:00
interval_b:1995-02-14T00:00:00.000-05:00/2001-05-18T00:00:00.000-04:00
period_b:P6Y3M4D
periodCombined:P27Y3M3W7D
periodCombinedNormalized:P27Y3M4W
如果您想使用仅限日期,没有时间或时区,那么您可以使用Joda-Time和java.time提供的LocalDate
类。 Joda-Time中方便的Interval
类不适用于LocalDate,但Period
可以使用。{/ p>
LocalDate start_a = new LocalDate( "1993-08-16" );
LocalDate stop_a = new LocalDate( "2014-09-09" );
Period period_a = new Period( start_a , stop_a );
LocalDate start_b = new LocalDate( "1995-02-14" );
LocalDate stop_b = new LocalDate( "2001-05-18" );
Period period_b = new Period( start_b , stop_b );
Period periodCombined = period_a.plus( period_b );
Period periodCombinedNormalized = periodCombined.normalizedStandard(); // Assumes that all years are 12 months, all weeks are 7 days, all days are 24 hours, all hours are 60 minutes and all minutes are 60 seconds. Not true for Daylight Saving Time and other anomalies.
如果要拼出输出,请使用DateTimeFormatterBuilder
类。使用如下代码:
DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
.appendMonthOfYearText()
.appendLiteral(' ')
.appendYear(4, 4)
.toFormatter();
搜索StackOverflow以获取使用该类的许多示例。