日期选择和发现差异 [英] Date picking and finding difference

查看:98
本文介绍了日期选择和发现差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Netbeans进行Java编程的新手.我已将jCalendar添加到我的GUI中以选择日期.

I am a novice to Java programming using Netbeans. I have added jCalendar to my GUI to pick a date.

我已经在jCalendar按钮的事件"->属性更改"代码中输入了此行,

I have entered this line in Events -> "property change" code of jCalendar button,

Date date=jcalendar1.getDate(); 

以便我可以在更改日期后立即获得日期.我说的对吗?

So that I get the date immediately when it is changed. Am I right?

目的: 我想找到从上述日期的下午(12:00 pm)到NOW(当前日期和时间)的毫秒数差异. 有几个程序显示日期差,但是所有程序都有硬编码的日期,作为一个新手,我不知道如何用选择的日期替换它. (同样,我对对象的日期和日历感到困惑,无法理解它们之间的区别).例如,来自这里的一块:

The purpose: I want to find the difference in milliseconds from the afternoon (12:00 pm) of this date above to NOW (current date and time). There are several programs showing the date difference but all have dates hardcoded and being a newbie i do not know how to replace it with the date that is picked. (also i am confused between the objects Date and Calendar, not able to understand the difference between them). For example, a piece from here:

http://www.java2s.com/Code/Java/数据类型/返回日期设置为最近一天可能的毫秒数.htm

if (day == null) day = new Date();
  cal.setTime(day);
  cal.set(Calendar.HOUR_OF_DAY, 12);
  cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
  cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
  cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
  return cal.getTime();

这里day是一个Date对象. cal(日历对象)如何与之链接以输入时间.应该如何首先定义校准对象?我如何在您的程序中使用它或您认为的其他任何方法.一段带有详细注释的代码会更有帮助 谢谢!

Here day is a Date object. How is cal (a calendar object) linked to it to enter the time. How should the cal object be defined first? How can I use this or anything else in your opinion for my program. A piece of code with detail comments will be more helpful thanks!

推荐答案

而不是使用:

Date day = new Date();

使用:

Calendar cal = Calendar.getInstance();
cal.set (...);
Date date = new Date(cal.getTimeInMillis());

值得将这些内容抽象到DateUtils类或类似的东西中,如下所示:

Worth abstracting this stuff out to a DateUtils class or similar, with something like the following:

public static Date create(int year, int month, int day, int hour, int minute, int second) {
    return new Date(getTimeInMillis(year, month, day, hour, minute, second));
}

public static long getTimeInMillis(int year, int month, int day, int hour, int minute, int second, int milliseconds) {
    Calendar cal = Calendar.getInstance();

    cal.clear();
    cal.set(year, month, day, hour, minute, second);
    cal.set(Calendar.MILLISECOND, milliseconds);

    return cal.getTimeInMillis();
}

这篇关于日期选择和发现差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆