|
|
||||
|
||||
|
|
||||
|
||||
|
|
|
|
||||
|
||||
|
|
||||
|
||||
|
|
Java Date and Time FAQ | |
|
When working with dates in Java, don't forget that a lot of questions can likely be answered by reading various class documentations. A few of the ones that are used frequently include Date, DateFormat, SimpleDateFormat, and Calendar:
Follow the links below for information on dealing with some common Date-related programming issues.
If you perform a lot of date-time operations, you might want to check out the Joda Time library.
Parsing a string into a date Parsing a String to a Date can be done with the DateFormat class. Note that you must include the seconds in the time in order for the LONG format to work. Also, you cannot use getTimeInstance with a string that includes anything other than a time, such as the date and time in d1, below:
If you only want to check for validity, or don't want to catch the ParseException, DateFormat has a second parse method that takes a ParsePosition:
Formatting dates If you want to format a Date into a String according to a format you want, you can use the SimpleDateFormat class. A simple example:
Daylight Savings Time This is a snippet of code that will convert from BST (British Summer Time) to GMT:
How many days in a given month? A little code snippet that calculates the number of days in a particular month, taking leap years into account.
Although the above works, java.util.Calendar has built-in support for this without hard-coding the number of days:
Deprecated methods in java.util.Date Do not shy away from java.util.Date just because it contains plenty of deprecated methods. They aren't deprecated because they produce incorrect results, but because a more powerful API is available with java.util.Calendar and its associated classes. If Date does what you need, you may wish to avoid the comparatively more complex Calendar class.
Note that Date objects do not have an associated timezone, though, so if you need to work with dates from different timezones, Calendar is a better choice. Also, Calendar takes Daylight Savings Time into account, whereas Date does not - that's important if you want to perform arithmetic on dates/times.
CategoryFaq | |