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

标签 java swing user-interface jlist

标题说明了一切,我需要能够让用户以月/日的形式输入开始日期和结束日期,并能够计算其间的周数。我想使用 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/

相关文章:

java - 换行在 JList 单元格内不起作用

javascript - 动态增长文本输入数组 (HTML/JavaScript)

java - blackberry - 将NegativeMarginVerticalFieldManager中的字段置于前面

java - 如何使用 getParent() 获取被点击组件的父对象?

javascript - 无法将数据从 firebase 实时数据库检索到网络应用程序

Java 仅从文本文件中抓取数字 : Integer. ParseInt 抛出 NumberFormatException

java - 最正确地利用了 SOLID 原则的 OSS .net/java 项目有哪些?

java - 复选框渲染器

java - 不同线程中的 Hibernate AssertionFailure

java - 显示鼠标坐标的标签