Class: SC.DateTime


Extends SC.Copyable, SC.Freezable, SC.Object.

A class representation of a date and time. It's basically a wrapper around the Date javascript object, KVO-friendly and with common date/time manipulation methods.

This object differs from the standard JS Date object, however, in that it supports time zones other than UTC and that local to the machine on which it is running. Any time zone can be specified when creating an SC.DateTime object, e.g.

// Creates a DateTime representing 5am in Washington, DC and 10am in London
var d = SC.DateTime.create({ hour: 5, timezone: 300 }); // -5 hours from UTC
var e = SC.DateTime.create({ hour: 10, timezone: 0 }); // same time, specified in UTC

and it is true that d.isEqual(e).

The time zone specified upon creation is permanent, and any calls to get() on that instance will return values expressed in that time zone. So,

d.get('hour') returns 5.
e.get('hour') returns 10.

but

d.get('milliseconds') === e.get('milliseconds')

is true, since they are technically the same position in time.

You can also use SC.DateTime as a record attribute on a data model.

SC.Record.attr(SC.DateTime); // Default format is ISO8601. See `SC.DateTime.recordFormat`
SC.Record.attr(SC.DateTime, { format: '%d/%m/%Y' }); // Attribute stored as a string in '%d/%m/%Y' format
SC.Record.attr(SC.DateTime, { useUnixTime: YES }); // Attribute stored as a number in Unix time

Defined in: datetime.js

Since:
SproutCore 1.0

Field Summary

Fields borrowed from SC.Object:
concatenatedProperties, isDestroyed, isObject, nextProperty, object, property, target, toInvalidate
Fields borrowed from SC.Observable:
isObservable
Fields borrowed from SC.Freezable:
isFreezable
Fields borrowed from SC.Copyable:
isCopyable

Class Methods

Instance Methods

Field Detail

SC.DateTime.abbreviatedDayNames Array
Default value:
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
SC.DateTime.abbreviatedMonthNames Array
Default value:
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
SC.DateTime.AMPMNames Array
Default value:
['AM', 'PM']
SC.DateTime.dayNames Array
Default value:
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
isFrozen Boolean
A `SC.DateTime` instance is frozen by default for better performance.
SC.DateTime.monthNames Array
Default value:
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
SC.DateTime.recordFormat String

The default format (ISO 8601) in which DateTimes are stored in a record. Change this value if your backend sends and receives dates in another format.

This value can also be customized on a per-attribute basis with the format property. For example:

SC.Record.attr(SC.DateTime, { format: '%d/%m/%Y %H:%M:%S' })
Default value:
SC.DATETIME_ISO8601
timezone Integer
SC.DateTime.timezone Integer

The offset, in minutes, between UTC and the local system time. This property is computed at loading time and should never be changed.

Default value:
new Date().getTimezoneOffset()

Class Method Detail

compare(a, b)

This will tell you which of the two passed DateTime is greater by comparing their number of milliseconds since January, 1st 1970 00:00:00.0 UTC.

Parameters:
a SC.DateTime
the first DateTime instance
b SC.DateTime
the second DateTime instance
Returns:
Integer

-1 if a < b, +1 if a > b, 0 if a == b

compareDate(a, b)

This will tell you which of the two passed DateTime is greater by only comparing the date parts of the passed objects. Only dates with the same timezone can be compared.

Parameters:
a SC.DateTime
the first DateTime instance
b SC.DateTime
the second DateTime instance
Returns:
Integer

-1 if a < b, +1 if a > b, 0 if a == b

Throws:
SC.DATETIME_COMPAREDATE_TIMEZONE_ERROR

if the passed arguments don't have the same timezone

create(options)

Returns a new SC.DateTime object advanced according the the given parameters. The parameters can be:

  • none, to create a SC.DateTime instance initialized to the current date and time in the local timezone,
  • a integer, the number of milliseconds since January, 1st 1970 00:00:00.0 UTC
  • a options hash that can contain any of the following properties: year, month, day, hour, minute, second, millisecond, timezone

Note that if you attempt to create a SC.DateTime instance that has already been created, then, for performance reasons, a cached value may be returned.

The timezone option is the offset, in minutes, between UTC and local time. If you don't pass a timezone option, the date object is created in the local timezone. If you want to create a UTC+2 (CEST) date, for example, then you should pass a timezone of -120.

Parameters:
options
one of the three kind of parameters described above
Returns:
SC.DateTime

the SC.DateTime instance that corresponds to the passed parameters, possibly fetched from cache

difference(a, b, format)

Returns the interval of time between the two passed in DateTimes in units according to the format.

You can display the difference in weeks (w), days (d), hours (h), minutes (M) or seconds (S).

Parameters:
a SC.DateTime
the first DateTime instance
b SC.DateTime
the second DateTime instance
format String
the interval to get the difference in
parse(str, fmt)

Returns a SC.DateTime object created from a given string parsed with a given format. Returns null if the parsing fails.

Parameters:
str String
the string to parse
fmt String
the format to parse the string with
Returns:
DateTime
the DateTime corresponding to the string parameter
See:
SC.DateTime#toFormattedString for a description of the format parameter

Instance Method Detail

adjust(options, resetCascadingly)

Returns a new SC.DateTime object where one or more of the elements have been adjusted according to the options parameter. The possible options that can be adjusted are timezone, year, month, day, hour, minute, second and millisecond.

This is particularly useful when we want to get to a certain date or time based on an existing date or time without having to know all the elements of the existing date.

For example, say we needed a datetime for midnight on whatever day we are given. The easiest way to do this is to take the datetime we are given and adjust it. For example,

var midnight = someDate.adjust({ hour: 24 }); // Midnight on whatever day `someDate` is.

Adjusting Time

The time options, hour, minute, second, millisecond, are reset cascadingly by default. So for example, if only the hour is passed, then the minute, second, and millisecond will be set to 0. Or for another example, if the hour and minute are passed, then second and millisecond would be set to 0. To disable this simply pass false as the second argument to adjust.

Adjusting Timezone

If a time zone is passed in the options hash, all dates and times are assumed to be local to it, and the returned SC.DateTime instance has that time zone. If none is passed, it defaults to the value of SC.DateTime.timezone.

Note that passing only a time zone does not affect the actual milliseconds since Jan 1, 1970, only the time zone in which it is expressed when displayed.

Parameters:
options Object
the amount of date/time to advance the receiver
resetCascadingly Boolean Optional
whether to reset the time elements cascadingly from hour down to millisecond. Default `true`.
Returns:
SC.DateTime
copy of receiver
advance(options)

Returns a new SC.DateTime object where one or more of the elements have been advanced according to the options parameter. The possible options that can be advanced are year, month, day, hour, minute, second and millisecond.

Note, you should not use floating point values as it might give unpredictable results.

Parameters:
options Object
the amount of date/time to advance the receiver
Returns:
DateTime
copy of the receiver
copy()

Returns a copy of the receiver. Because of the way SC.DateTime is designed, it just returns the receiver.

Returns:
SC.DateTime
dayOrdinal()

Returns the suffix of the date for use in english eg 21st 22nd 22rd speech.

Returns:
String
isEqual(aDateTime)

Returns YES if the passed SC.DateTime is equal to the receiver, ie: if their number of milliseconds since January, 1st 1970 00:00:00.0 UTC are equal. This is the preferred method for testing equality.

Parameters:
aDateTime SC.DateTime
the DateTime to compare to
Returns:
Boolean
See:
SC.DateTime#compare
toFormattedString(format)

Formats the receiver according to the given format string. Should behave like the C strftime function.

The format parameter can contain the following characters:

  • %a -- The abbreviated weekday name ("Sun")
  • %A -- The full weekday name ("Sunday")
  • %b -- The abbreviated month name ("Jan")
  • %B -- The full month name ("January")
  • %c -- The preferred local date and time representation
  • %d -- Day of the month (01..31)
  • %D -- Day of the month (0..31)
  • %E -- Elapsed time, according to localized text formatting strings. See below.
  • %h -- Hour of the day, 24-hour clock (0..23)
  • %H -- Hour of the day, 24-hour clock (00..23)
  • %i -- Hour of the day, 12-hour clock (1..12)
  • %I -- Hour of the day, 12-hour clock (01..12)
  • %j -- Day of the year (001..366)
  • %m -- Month of the year (01..12)
  • %M -- Minute of the hour (00..59)
  • %o -- The day's ordinal abbreviation ('st', 'nd', 'rd', etc.)
  • %p -- Meridian indicator ("AM" or "PM")
  • %S -- Second of the minute (00..60)
  • %s -- Milliseconds of the second (000..999)
  • %U -- Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
  • %W -- Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
  • %w -- Day of the week (Sunday is 0, 0..6)
  • %x -- Preferred representation for the date alone, no time
  • %X -- Preferred representation for the time alone, no date
  • %y -- Year without a century (00..99)
  • %Y -- Year with century
  • %Z -- Time zone (ISO 8601 formatted)
  • %% -- Literal "%" character

The Elapsed date format is a special, SproutCore specific formatting feature which will return an accurate-ish, human readable indication of elapsed time. For example, it might return "In 5 minutes", or "A year ago".

For example,

var date = SC.DateTime.create();

date.toFormattedString("%E"); // "Right now"

date.advance({ minute: 4 });
date.toFormattedString("%E"); // "In 4 minutes"

date.advance({ day: -7 });
date.toFormattedString("%E"); // "About a week ago"

To customize the output for the %E formatter, override the date localization strings inside of in your app. The English localization strings used are:

'_SC.DateTime.now' : 'Right now',
'_SC.DateTime.secondIn' : 'In a moment',
'_SC.DateTime.secondsIn' : 'In %e seconds',
'_SC.DateTime.minuteIn' : 'In a minute',
'_SC.DateTime.minutesIn' : 'In %e minutes',
'_SC.DateTime.hourIn' : 'An hour from now',
'_SC.DateTime.hoursIn' : 'In about %e hours',
'_SC.DateTime.dayIn' : 'Tomorrow at %i:%M %p',
'_SC.DateTime.daysIn' : '%A at %i:%M %p',
'_SC.DateTime.weekIn' : 'Next week',
'_SC.DateTime.weeksIn' : 'In %e weeks',
'_SC.DateTime.monthIn' : 'Next month',
'_SC.DateTime.monthsIn' : 'In %e months',
'_SC.DateTime.yearIn' : 'Next year',
'_SC.DateTime.yearsIn' : 'In %e years',

'_SC.DateTime.secondAgo' : 'A moment ago',
'_SC.DateTime.secondsAgo' : '%e seconds ago',
'_SC.DateTime.minuteAgo' : 'A minute ago',
'_SC.DateTime.minutesAgo' : '%e minutes ago',
'_SC.DateTime.hourAgo' : 'An hour ago',
'_SC.DateTime.hoursAgo' : 'About %e hours ago',
'_SC.DateTime.dayAgo' : 'Yesterday at %i:%M %p',
'_SC.DateTime.daysAgo' : '%A at %i:%M %p',
'_SC.DateTime.weekAgo' : 'About a week ago',
'_SC.DateTime.weeksAgo' : '%e weeks ago',
'_SC.DateTime.monthAgo' : 'About a month ago',
'_SC.DateTime.monthsAgo' : '%e months ago',
'_SC.DateTime.yearAgo' : 'Last year',
'_SC.DateTime.yearsAgo' : '%e years ago'

Notice the special "%e" parameter in the localized strings. This will be replaced with the number of intervals (seconds, minutes, weeks, etc) that are appropriate.

Parameters:
format String
the format string
Returns:
String
the formatted string
toISO8601()

Formats the receiver according ISO 8601 standard. It is equivalent to calling toFormattedString with the '%Y-%m-%dT%H:%M:%S%Z' format string.

Returns:
String
the formatted string
toTimezone(timezone)

Returns a copy of the receiver with the timezone set to the passed timezone. The returned value is equal to the receiver (ie SC.Compare returns 0), it is just the timezone representation that changes.

If you don't pass any argument, the target timezone is assumed to be 0, ie UTC.

Note that this method does not change the underlying position in time, but only the time zone in which it is displayed. In other words, the underlying number of milliseconds since Jan 1, 1970 does not change.

Parameters:
timezone
Returns:
SC.DateTime
unknownProperty(key)

Generic getter.

The properties you can get are:

  • year
  • month (January is 1, contrary to JavaScript Dates for which January is 0)
  • day
  • dayOfWeek (Sunday is 0)
  • hour
  • minute
  • second
  • millisecond
  • milliseconds, the number of milliseconds since January, 1st 1970 00:00:00.0 UTC
  • elapsed, the number of milliseconds until (-), or since (+), the date.
  • isLeapYear, a boolean value indicating whether the receiver's year is a leap year
  • daysInMonth, the number of days of the receiver's current month
  • dayOfYear, January 1st is 1, December 31th is 365 for a common year
  • week or week1, the week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
  • week0, the week number of the current year, starting with the first Monday as the first day of the first week (00..53)
  • lastMonday, lastTuesday, etc., nextMonday, nextTuesday, etc., the date of the last or next weekday in comparison to the receiver.
Parameters:
key String
the property name to get
Returns:
the value asked for
Documentation generated by JsDoc Toolkit 2.4.0 on Wed Apr 08 2015 10:02:20 GMT-0600 (CST)