Wednesday, 29 August 2012

Time, Date, and Datetime - Apex

There are three data types associated with dates and times. The Time data type stores times (hours, minutes, second and milliseconds). The Date data type stores dates (year, month and day). The Datetime data type stores both dates and times.
Each of these classes has a newInstance method with which you can construct particular date and time values. For example, execute the following:
Date myDate = Date.newinstance(1960, 2, 17);
Time myTime = Time.newInstance(18, 30, 2, 20);
This outputs:
1960-02-17 00:00:00
The Date data type does hold a time, even though it's set to 0 by default.
You can also create dates and times from the current clock:
Datetime myDateTime =;
Date today =;
The date and time classes also have instance methods for converting from one format to another. For example:
Time  t =;
Finally, you can also manipulate and interrogate the values by using a range of instance methods. For example, Datetime has the addHoursaddMinutes,dayOfYeartimeGMT methods and many others. Execute the following:
Date myToday   =;
Date myNext30 = myToday.addDays(30);
System.debug('myToday =  ' + myToday);
System.debug('myNext30=  ' + myNext30);
You'll get something like this as the output.
2012-02-09 00:00:00
2011-03-10 00:00:00

1 comment: