Skip to content
Advertisement

SWT DateTime – read date and time from two widgets

Imagine two widgets:

DateTime dtDate = new DateTime(parent, SWT.BORDER);

and

DateTime dtTime = new DateTime(parent, SWT.BORDER | SWT.TIME);

Would would be the most efficient way to read date and time from the two widgets into a single Date variable?

Edit: The following solution that I have in mind is far from being elegant. I hope that there is a better way to do this.

final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// year
dateString += String.valueOf(dtDate .getYear());
dateString += "-";
// month
dateString += String.valueOf(dtDate .getMonth());
dateString += "-";

// day
dateString += String.valueOf(dtDate .getDay());
dateString += " ";

// hour
dateString += String.valueOf(dtTime.getHours());
dateString += ":";

// minute
dateString += String.valueOf(dtTime.getMinutes());
dateString += ":";

// second
dateString += String.valueOf(dtTime.getSeconds());

try {
    Date startDate = (Date) dateFormat.parse(dateString);
    } catch (ParseException exception) {
    exception.printStackTrace();
    }

Advertisement

Answer

For Java 8 and later you can use LocalDateTime:

LocalDateTime dateTime = 
   LocalDateTime.of(dtDate.getYear(), dtDate.getMonth() + 1, dtDate.getDay(), dtTime.getHours(), dtTime.getMinutes(), dtTime.getSeconds());

The JFace data binding uses Calendar:

Calendar cal = Calendar.getInstance();
cal.clear();

cal.set(Calendar.YEAR, dtDate.getYear());
cal.set(Calendar.MONTH, dtDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, dtDate.getDay());

cal.set(Calendar.HOUR_OF_DAY, dtTime.getHours());
cal.set(Calendar.MINUTE, dtTime.getMinutes());
cal.set(Calendar.SECOND, dtTime.getSeconds());

Date date = cal.getTime();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement