Date picking and finding difference

烂漫一生 提交于 2019-12-10 23:37:27

问题


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

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?

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/Data-type/ReturnsaDatesetjusttoNoontotheclosestpossiblemillisecondoftheday.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();

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!


回答1:


Instead of using :

Date day = new Date();

Use:

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

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();
}


来源:https://stackoverflow.com/questions/10395351/date-picking-and-finding-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!