自动增加SWT日期时间

时间:2014-11-13 12:29:01

标签: java datetime swt

在我的程序中,我有两个org.eclipse.swt.widgets.DateTime小部件。如果更改了一个(日,月或年),则另一个应设置为增加两天的相同日期。

例如,一个设置为01.01.2014,另一个设置应跳转到03.01.2014

是否有任何解决方案,或者您是否知道有关此问题的任何摘录?我不想总是检查第一个DateTime是否设置为月末,以便第二个应该跳转到01.02.201402.02.2014 ... < / p>

我希望你明白我在寻找什么;)

2 个答案:

答案 0 :(得分:3)

您可以使用java.util.Calendar,特别是add(int, int)方法,将{2}添加到Calendar.DAY_OF_YEAR。它将自动移至下个月/年:

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell();
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(2, false));

    final DateTime first = new DateTime(shell, SWT.CALENDAR);
    final DateTime second = new DateTime(shell, SWT.CALENDAR);

    first.addListener(SWT.Selection, new Listener()
    {
        private Calendar cal = Calendar.getInstance();

        @Override
        public void handleEvent(Event arg0)
        {
            cal.set(Calendar.YEAR, first.getYear());
            cal.set(Calendar.MONTH, first.getMonth());
            cal.set(Calendar.DAY_OF_MONTH, first.getDay());

            cal.add(Calendar.DAY_OF_YEAR, 2);

            second.setDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
        }
    });

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();
}

答案 1 :(得分:0)

使用java.util.Calendar

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 2);
相关问题