ToDate()
function ToDate(timeValue: Date | TimeStamp | number): Date;Converts a timestamp into a native JavaScript Date object, so you can use all the standard JavaScript date and time methods on it.
This is what you reach for when a SyncJS function hands you a TimeStamp. Every DirListItem carries one, from StatFileSystemObject, from ListDir and ListDirR, from a VFS Stat().Info() or ReadDir().Infos(), and from a remote client listing. A TimeStamp is a value from the host process, not a JavaScript Date: it has no getTime() and no toISOString() until you convert it.
Parameters
| Name | Type | Description |
|---|---|---|
timeValue | Date, TimeStamp or number | What to convert. See the accepted values below. |
Accepted values
| You pass | Result |
|---|---|
A JavaScript Date | An equivalent Date |
A TimeStamp from a listing, a stat, or any VFS or remote client response | A Date for that moment |
| A number | Read as epoch milliseconds |
| A string | Parsed as RFC 3339, or YYYY-MM-DD HH:mm:ss, or YYYY-MM-DD |
Returns
A native JavaScript Date representing the same point in time as the input.
A value that cannot be converted raises an error your script can catch. undefined and null cannot be converted either, so guard a value you are not sure about.
Example
var info = StatFileSystemObject("/home/myself/Documents/brochure.pdf");
if (info.Name !== "") {
var ts = ToDate(info.TimeStamp);
// Use ts as any other native JavaScript Date object
Log(ts.toISOString());
Log("age in days: " + Math.floor((Date.now() - ts.getTime()) / 86400000));
}Example: handling an uncertain value
try {
var when = ToDate(maybeATimestamp);
Log(when.toISOString());
} catch (e) {
Log.Warn("not a timestamp: " + e);
}IMPORTANT
Earlier builds of the SyncJS engine asserted a bare time.Time here. A TimeStamp read from a struct field reaches the script as a pointer, so the assertion missed the common case and ToDate(info.TimeStamp), exactly as shown above, stopped the script with an error that no try/catch could see. It is fixed: the conversion accepts every value in the table above, and an unconvertible one raises a catchable error instead of tearing the execution down.
See also
FormatDateTime: format a timestamp directly, without converting it firstDirListItem: where aTimeStampcomes from
