简体   繁体   中英

Building a date from year, month and day in GWT

I need to build a Date from year, month and day in GWT. How can I do that without the use of Calendar , as it is not available in GWT?

You can use java.util.Date

Date date = new Date();
date.setYear(year);   // setting year
date.setMonth(month); // setting month
date.setDate(date);   // setting day of month

If you don't want to have any other fields:

date.setHours(0);   // setting hours to 0
date.setMinutes(0); // setting minutes to 0
date.setSeconds(0); // setting seconds to 0

This way your code can still have milliseconds, however you could easily get rid of it:

long time = date.getTime();    // getting timestamp
time = (time / 1000L) * 1000L; // getting rid of milliseconds by integer division
                               // or alternatively
time -= time % 1000L;          // getting rid of milliseconds by substracting remainder
date.setTime(time);            // setting the timestamp without milliseconds

You could use the second method to get rid of hours, minutes, seconds and milliseconds too, but it wouldn't be precise because of the leap seconds.

Note: these methods (except getTime() and setTime() ) are deprecated, but this may be the most straightforward way to do this in GWT.

Use DateTimeFormat that provide Internationalization also.

    DateTimeFormat format=DateTimeFormat.getFormat("dd/MM/yyyy");
    Date date=format.parse("03/11/2014");
    System.out.println(date);

Output:

Mon Nov 03 00:00:00 IST 2014

For more info read about GWT DateTimeFormat .

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