gpt4 book ai didi

java - 使用 Java Swing 计算开始日期和结束日期之间的周数

转载 作者:行者123 更新时间:2023-12-01 14:17:10 30 4
gpt4 key购买 nike

标题说明了一切,我需要能够让用户以月/日的形式输入开始日期和结束日期,并能够计算其间的周数。我想使用 JList 来解决这个问题,但似乎 JList 只适用于字符串。

我会使用什么 Swing 函数,任何帮助将不胜感激,谢谢!

最佳答案

您的问题与 Swing 无关。

使用JodaTime为了您的目的

import org.joda.time.LocalDateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

....
public static Map<Integer, String> getDateTimeDiffMap(String dateA, String dateB) {

Calendar cal = Calendar.getInstance();
Map<Integer,String> out = new LinkedHashMap<Integer, String>();

long timeInMillA = 0;
long timeInMillB = 0;

SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

Date convertedDateA;
Date convertedDateB;

try {
convertedDateA = dateFormat.parse(dateA);
cal.setTime(convertedDateA);
timeInMillA = cal.getTimeInMillis();


convertedDateB = dateFormat.parse(dateB);
cal.setTime(convertedDateB);
timeInMillB = cal.getTimeInMillis();

} catch (ParseException e) {
e.printStackTrace();
}


LocalDateTime startA = new LocalDateTime(timeInMillA);
LocalDateTime startB = new LocalDateTime(timeInMillB);

Period difference = new Period(startA, startB, PeriodType.days());
int day = difference.getDays();

difference = new Period(startA, startB, PeriodType.months());
int month = difference.getMonths();

difference = new Period(startA, startB, PeriodType.years());
int year = difference.getYears();

difference = new Period(startA, startB, PeriodType.weeks());
int week = difference.getWeeks();

difference = new Period(startA, startB, PeriodType.hours());
int hour = difference.getHours();

difference = new Period(startA, startB, PeriodType.minutes());
long min = difference.getMinutes();

difference = new Period(startA, startB, PeriodType.seconds());
long sec = difference.getSeconds();

//difference = new Period(startA, startB, PeriodType.millis());
long mili = timeInMillB - timeInMillA;


out.put(7, mili + "");
out.put(6, sec + "");
out.put(5, min + "");
out.put(4, hour + "");
out.put(3, day + "");
out.put(2, week + "");
out.put(1, month + "");
out.put(0, year + "");

return out;
}

例如,对于“01-09-2012 20:9:01”、“01-10-2012 20:9:01”,我得到输出:

year=0;
month = 1;
day=30;
hour=720;
...

关于java - 使用 Java Swing 计算开始日期和结束日期之间的周数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18026313/

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