简体   繁体   中英

Increase the date of a SWT Datetime automatically

In my program I have two org.eclipse.swt.widgets.DateTime widgets. If the one is changed (day, month or year) the other one should be set to the same date increased by two days.

For example the one is set to 01.01.2014 the other one should jump to 03.01.2014 .

Is there any solution, or do you know any snippets about that? I don't want to check always if the first DateTime is set to the end of a month, so that the second one should jump to 01.02.2014 or 02.02.2014 ...

I hope you understand what I am searching for ;)

You can use java.util.Calendar and in particular the method add(int, int) to add two to Calendar.DAY_OF_YEAR . It will move to the next month/year automatically:

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

Use java.util.Calendar :

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM