/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
/**
* This class implements the Date native object.
* See ECMA 15.9.
* @author Mike McCabe
*
* Significant parts of this code are adapted from the venerable jsdate.cpp (also Mozilla):
* https://dxr.mozilla.org/mozilla-central/source/js/src/jsdate.cpp
*/
final class NativeDate extends IdScriptableObject
{
static final long serialVersionUID = -8307438915861678966L;
private static final Object DATE_TAG = "Date";
private static final String js_NaN_date_str = "Invalid Date";
static void init(Scriptable scope, boolean sealed)
{
NativeDate obj = new NativeDate();
// Set the value of the prototype Date to NaN ('invalid date');
obj.date = ScriptRuntime.NaN;
obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
private NativeDate()
{
if (thisTimeZone == null) {
// j.u.TimeZone is synchronized, so setting class statics from it
// should be OK.
thisTimeZone = TimeZone.getDefault();
LocalTZA = thisTimeZone.getRawOffset();
}
}
@Override
public String getClassName()
{
return "Date";
}
@Override
public Object getDefaultValue(Class> typeHint)
{
if (typeHint == null)
typeHint = ScriptRuntime.StringClass;
return super.getDefaultValue(typeHint);
}
double getJSTimeValue()
{
return date;
}
@Override
protected void fillConstructorProperties(IdFunctionObject ctor)
{
addIdFunctionProperty(ctor, DATE_TAG, ConstructorId_now,
"now", 0);
addIdFunctionProperty(ctor, DATE_TAG, ConstructorId_parse,
"parse", 1);
addIdFunctionProperty(ctor, DATE_TAG, ConstructorId_UTC,
"UTC", 7);
super.fillConstructorProperties(ctor);
}
@Override
protected void initPrototypeId(int id)
{
String s;
int arity;
switch (id) {
case Id_constructor: arity=7; s="constructor"; break;
case Id_toString: arity=0; s="toString"; break;
case Id_toTimeString: arity=0; s="toTimeString"; break;
case Id_toDateString: arity=0; s="toDateString"; break;
case Id_toLocaleString: arity=0; s="toLocaleString"; break;
case Id_toLocaleTimeString: arity=0; s="toLocaleTimeString"; break;
case Id_toLocaleDateString: arity=0; s="toLocaleDateString"; break;
case Id_toUTCString: arity=0; s="toUTCString"; break;
case Id_toSource: arity=0; s="toSource"; break;
case Id_valueOf: arity=0; s="valueOf"; break;
case Id_getTime: arity=0; s="getTime"; break;
case Id_getYear: arity=0; s="getYear"; break;
case Id_getFullYear: arity=0; s="getFullYear"; break;
case Id_getUTCFullYear: arity=0; s="getUTCFullYear"; break;
case Id_getMonth: arity=0; s="getMonth"; break;
case Id_getUTCMonth: arity=0; s="getUTCMonth"; break;
case Id_getDate: arity=0; s="getDate"; break;
case Id_getUTCDate: arity=0; s="getUTCDate"; break;
case Id_getDay: arity=0; s="getDay"; break;
case Id_getUTCDay: arity=0; s="getUTCDay"; break;
case Id_getHours: arity=0; s="getHours"; break;
case Id_getUTCHours: arity=0; s="getUTCHours"; break;
case Id_getMinutes: arity=0; s="getMinutes"; break;
case Id_getUTCMinutes: arity=0; s="getUTCMinutes"; break;
case Id_getSeconds: arity=0; s="getSeconds"; break;
case Id_getUTCSeconds: arity=0; s="getUTCSeconds"; break;
case Id_getMilliseconds: arity=0; s="getMilliseconds"; break;
case Id_getUTCMilliseconds: arity=0; s="getUTCMilliseconds"; break;
case Id_getTimezoneOffset: arity=0; s="getTimezoneOffset"; break;
case Id_setTime: arity=1; s="setTime"; break;
case Id_setMilliseconds: arity=1; s="setMilliseconds"; break;
case Id_setUTCMilliseconds: arity=1; s="setUTCMilliseconds"; break;
case Id_setSeconds: arity=2; s="setSeconds"; break;
case Id_setUTCSeconds: arity=2; s="setUTCSeconds"; break;
case Id_setMinutes: arity=3; s="setMinutes"; break;
case Id_setUTCMinutes: arity=3; s="setUTCMinutes"; break;
case Id_setHours: arity=4; s="setHours"; break;
case Id_setUTCHours: arity=4; s="setUTCHours"; break;
case Id_setDate: arity=1; s="setDate"; break;
case Id_setUTCDate: arity=1; s="setUTCDate"; break;
case Id_setMonth: arity=2; s="setMonth"; break;
case Id_setUTCMonth: arity=2; s="setUTCMonth"; break;
case Id_setFullYear: arity=3; s="setFullYear"; break;
case Id_setUTCFullYear: arity=3; s="setUTCFullYear"; break;
case Id_setYear: arity=1; s="setYear"; break;
case Id_toISOString: arity=0; s="toISOString"; break;
case Id_toJSON: arity=1; s="toJSON"; break;
default: throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(DATE_TAG, id, s, arity);
}
@Override
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!f.hasTag(DATE_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
switch (id) {
case ConstructorId_now:
return ScriptRuntime.wrapNumber(now());
case ConstructorId_parse:
{
String dataStr = ScriptRuntime.toString(args, 0);
return ScriptRuntime.wrapNumber(date_parseString(dataStr));
}
case ConstructorId_UTC:
return ScriptRuntime.wrapNumber(jsStaticFunction_UTC(args));
case Id_constructor:
{
// if called as a function, just return a string
// representing the current time.
if (thisObj != null)
return date_format(now(), Id_toString);
return jsConstructor(args);
}
case Id_toJSON:
{
final String toISOString = "toISOString";
Scriptable o = ScriptRuntime.toObject(cx, scope, thisObj);
Object tv = ScriptRuntime.toPrimitive(o, ScriptRuntime.NumberClass);
if (tv instanceof Number) {
double d = ((Number) tv).doubleValue();
if (d != d || Double.isInfinite(d)) {
return null;
}
}
Object toISO = ScriptableObject.getProperty(o, toISOString);
if (toISO == NOT_FOUND) {
throw ScriptRuntime.typeError2("msg.function.not.found.in",
toISOString,
ScriptRuntime.toString(o));
}
if ( !(toISO instanceof Callable) ) {
throw ScriptRuntime.typeError3("msg.isnt.function.in",
toISOString,
ScriptRuntime.toString(o),
ScriptRuntime.toString(toISO));
}
Object result = ((Callable) toISO).call(cx, scope, o,
ScriptRuntime.emptyArgs);
if ( !ScriptRuntime.isPrimitive(result) ) {
throw ScriptRuntime.typeError1("msg.toisostring.must.return.primitive",
ScriptRuntime.toString(result));
}
return result;
}
}
// The rest of Date.prototype methods require thisObj to be Date
if (!(thisObj instanceof NativeDate))
throw incompatibleCallError(f);
NativeDate realThis = (NativeDate)thisObj;
double t = realThis.date;
switch (id) {
case Id_toString:
case Id_toTimeString:
case Id_toDateString:
if (t == t) {
return date_format(t, id);
}
return js_NaN_date_str;
case Id_toLocaleString:
case Id_toLocaleTimeString:
case Id_toLocaleDateString:
if (t == t) {
return toLocale_helper(t, id);
}
return js_NaN_date_str;
case Id_toUTCString:
if (t == t) {
return js_toUTCString(t);
}
return js_NaN_date_str;
case Id_toSource:
return "(new Date("+ScriptRuntime.toString(t)+"))";
case Id_valueOf:
case Id_getTime:
return ScriptRuntime.wrapNumber(t);
case Id_getYear:
case Id_getFullYear:
case Id_getUTCFullYear:
if (t == t) {
if (id != Id_getUTCFullYear) t = LocalTime(t);
t = YearFromTime(t);
if (id == Id_getYear) {
if (cx.hasFeature(Context.FEATURE_NON_ECMA_GET_YEAR)) {
if (1900 <= t && t < 2000) {
t -= 1900;
}
} else {
t -= 1900;
}
}
}
return ScriptRuntime.wrapNumber(t);
case Id_getMonth:
case Id_getUTCMonth:
if (t == t) {
if (id == Id_getMonth) t = LocalTime(t);
t = MonthFromTime(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getDate:
case Id_getUTCDate:
if (t == t) {
if (id == Id_getDate) t = LocalTime(t);
t = DateFromTime(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getDay:
case Id_getUTCDay:
if (t == t) {
if (id == Id_getDay) t = LocalTime(t);
t = WeekDay(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getHours:
case Id_getUTCHours:
if (t == t) {
if (id == Id_getHours) t = LocalTime(t);
t = HourFromTime(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getMinutes:
case Id_getUTCMinutes:
if (t == t) {
if (id == Id_getMinutes) t = LocalTime(t);
t = MinFromTime(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getSeconds:
case Id_getUTCSeconds:
if (t == t) {
if (id == Id_getSeconds) t = LocalTime(t);
t = SecFromTime(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getMilliseconds:
case Id_getUTCMilliseconds:
if (t == t) {
if (id == Id_getMilliseconds) t = LocalTime(t);
t = msFromTime(t);
}
return ScriptRuntime.wrapNumber(t);
case Id_getTimezoneOffset:
if (t == t) {
t = (t - LocalTime(t)) / msPerMinute;
}
return ScriptRuntime.wrapNumber(t);
case Id_setTime:
t = TimeClip(ScriptRuntime.toNumber(args, 0));
realThis.date = t;
return ScriptRuntime.wrapNumber(t);
case Id_setMilliseconds:
case Id_setUTCMilliseconds:
case Id_setSeconds:
case Id_setUTCSeconds:
case Id_setMinutes:
case Id_setUTCMinutes:
case Id_setHours:
case Id_setUTCHours:
t = makeTime(t, args, id);
realThis.date = t;
return ScriptRuntime.wrapNumber(t);
case Id_setDate:
case Id_setUTCDate:
case Id_setMonth:
case Id_setUTCMonth:
case Id_setFullYear:
case Id_setUTCFullYear:
t = makeDate(t, args, id);
realThis.date = t;
return ScriptRuntime.wrapNumber(t);
case Id_setYear:
{
double year = ScriptRuntime.toNumber(args, 0);
if (year != year || Double.isInfinite(year)) {
t = ScriptRuntime.NaN;
} else {
if (t != t) {
t = 0;
} else {
t = LocalTime(t);
}
if (year >= 0 && year <= 99)
year += 1900;
double day = MakeDay(year, MonthFromTime(t),
DateFromTime(t));
t = MakeDate(day, TimeWithinDay(t));
t = internalUTC(t);
t = TimeClip(t);
}
}
realThis.date = t;
return ScriptRuntime.wrapNumber(t);
case Id_toISOString:
if (t == t) {
return js_toISOString(t);
}
String msg = ScriptRuntime.getMessage0("msg.invalid.date");
throw ScriptRuntime.constructError("RangeError", msg);
default: throw new IllegalArgumentException(String.valueOf(id));
}
}
/* ECMA helper functions */
private static final double HalfTimeDomain = 8.64e15;
private static final double HoursPerDay = 24.0;
private static final double MinutesPerHour = 60.0;
private static final double SecondsPerMinute = 60.0;
private static final double msPerSecond = 1000.0;
private static final double MinutesPerDay = (HoursPerDay * MinutesPerHour);
private static final double SecondsPerDay = (MinutesPerDay * SecondsPerMinute);
private static final double SecondsPerHour = (MinutesPerHour * SecondsPerMinute);
private static final double msPerDay = (SecondsPerDay * msPerSecond);
private static final double msPerHour = (SecondsPerHour * msPerSecond);
private static final double msPerMinute = (SecondsPerMinute * msPerSecond);
private static double Day(double t)
{
return Math.floor(t / msPerDay);
}
private static double TimeWithinDay(double t)
{
double result;
result = t % msPerDay;
if (result < 0)
result += msPerDay;
return result;
}
private static boolean IsLeapYear(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
/* math here has to be f.p, because we need
* floor((1968 - 1969) / 4) == -1
*/
private static double DayFromYear(double y)
{
return ((365 * ((y)-1970) + Math.floor(((y)-1969)/4.0)
- Math.floor(((y)-1901)/100.0) + Math.floor(((y)-1601)/400.0)));
}
private static double TimeFromYear(double y)
{
return DayFromYear(y) * msPerDay;
}
private static int YearFromTime(double t)
{
if (Double.isInfinite(t) || Double.isNaN(t)) {
return 0;
}
double y = Math.floor(t / (msPerDay * 365.2425)) + 1970;
double t2 = TimeFromYear(y);
/*
* Adjust the year if the approximation was wrong. Since the year was
* computed using the average number of ms per year, it will usually
* be wrong for dates within several hours of a year transition.
*/
if (t2 > t) {
y--;
} else {
if (t2 + msPerDay * DaysInYear(y) <= t)
y++;
}
return (int)y;
}
private static double DayFromMonth(int m, int year)
{
int day = m * 30;
if (m >= 7) { day += m / 2 - 1; }
else if (m >= 2) { day += (m - 1) / 2 - 1; }
else { day += m; }
if (m >= 2 && IsLeapYear(year)) { ++day; }
return day;
}
private static double DaysInYear(double year)
{
if (Double.isInfinite(year) || Double.isNaN(year)) {
return ScriptRuntime.NaN;
}
return IsLeapYear((int)year) ? 366.0 : 365.0;
}
private static int DaysInMonth(int year, int month)
{
// month is 1-based for DaysInMonth!
if (month == 2)
return IsLeapYear(year) ? 29 : 28;
return month >= 8
? 31 - (month & 1)
: 30 + (month & 1);
}
private static int MonthFromTime(double t)
{
int year = YearFromTime(t);
int d = (int)(Day(t) - DayFromYear(year));
d -= 31 + 28;
if (d < 0) {
return (d < -28) ? 0 : 1;
}
if (IsLeapYear(year)) {
if (d == 0)
return 1; // 29 February
--d;
}
// d: date count from 1 March
int estimate = d / 30; // approx number of month since March
int mstart;
switch (estimate) {
case 0: return 2;
case 1: mstart = 31; break;
case 2: mstart = 31+30; break;
case 3: mstart = 31+30+31; break;
case 4: mstart = 31+30+31+30; break;
case 5: mstart = 31+30+31+30+31; break;
case 6: mstart = 31+30+31+30+31+31; break;
case 7: mstart = 31+30+31+30+31+31+30; break;
case 8: mstart = 31+30+31+30+31+31+30+31; break;
case 9: mstart = 31+30+31+30+31+31+30+31+30; break;
case 10: return 11; //Late december
default: throw Kit.codeBug();
}
// if d < mstart then real month since March == estimate - 1
return (d >= mstart) ? estimate + 2 : estimate + 1;
}
private static int DateFromTime(double t)
{
int year = YearFromTime(t);
int d = (int)(Day(t) - DayFromYear(year));
d -= 31 + 28;
if (d < 0) {
return (d < -28) ? d + 31 + 28 + 1 : d + 28 + 1;
}
if (IsLeapYear(year)) {
if (d == 0)
return 29; // 29 February
--d;
}
// d: date count from 1 March
int mdays, mstart;
switch (Math.round(d / 30)) { // approx number of month since March
case 0: return d + 1;
case 1: mdays = 31; mstart = 31; break;
case 2: mdays = 30; mstart = 31+30; break;
case 3: mdays = 31; mstart = 31+30+31; break;
case 4: mdays = 30; mstart = 31+30+31+30; break;
case 5: mdays = 31; mstart = 31+30+31+30+31; break;
case 6: mdays = 31; mstart = 31+30+31+30+31+31; break;
case 7: mdays = 30; mstart = 31+30+31+30+31+31+30; break;
case 8: mdays = 31; mstart = 31+30+31+30+31+31+30+31; break;
case 9: mdays = 30; mstart = 31+30+31+30+31+31+30+31+30; break;
case 10:
return d - (31+30+31+30+31+31+30+31+30) + 1; //Late december
default: throw Kit.codeBug();
}
d -= mstart;
if (d < 0) {
// wrong estimate: sfhift to previous month
d += mdays;
}
return d + 1;
}
private static int WeekDay(double t)
{
double result;
result = Day(t) + 4;
result = result % 7;
if (result < 0)
result += 7;
return (int) result;
}
private static double now()
{
return System.currentTimeMillis();
}
private static double DaylightSavingTA(double t)
{
// Another workaround! The JRE doesn't seem to know about DST
// before year 1 AD, so we map to equivalent dates for the
// purposes of finding DST. To be safe, we do this for years
// before 1970.
if (t < 0.0) {
int year = EquivalentYear(YearFromTime(t));
double day = MakeDay(year, MonthFromTime(t), DateFromTime(t));
t = MakeDate(day, TimeWithinDay(t));
}
Date date = new Date((long) t);
if (thisTimeZone.inDaylightTime(date))
return msPerHour;
else
return 0;
}
/*
* Find a year for which any given date will fall on the same weekday.
*
* This function should be used with caution when used other than
* for determining DST; it hasn't been proven not to produce an
* incorrect year for times near year boundaries.
*/
private static int EquivalentYear(int year)
{
int day = (int) DayFromYear(year) + 4;
day = day % 7;
if (day < 0)
day += 7;
// Years and leap years on which Jan 1 is a Sunday, Monday, etc.
if (IsLeapYear(year)) {
switch (day) {
case 0: return 1984;
case 1: return 1996;
case 2: return 1980;
case 3: return 1992;
case 4: return 1976;
case 5: return 1988;
case 6: return 1972;
}
} else {
switch (day) {
case 0: return 1978;
case 1: return 1973;
case 2: return 1985;
case 3: return 1986;
case 4: return 1981;
case 5: return 1971;
case 6: return 1977;
}
}
// Unreachable
throw Kit.codeBug();
}
private static double LocalTime(double t)
{
return t + LocalTZA + DaylightSavingTA(t);
}
private static double internalUTC(double t)
{
return t - LocalTZA - DaylightSavingTA(t - LocalTZA);
}
private static int HourFromTime(double t)
{
double result;
result = Math.floor(t / msPerHour) % HoursPerDay;
if (result < 0)
result += HoursPerDay;
return (int) result;
}
private static int MinFromTime(double t)
{
double result;
result = Math.floor(t / msPerMinute) % MinutesPerHour;
if (result < 0)
result += MinutesPerHour;
return (int) result;
}
private static int SecFromTime(double t)
{
double result;
result = Math.floor(t / msPerSecond) % SecondsPerMinute;
if (result < 0)
result += SecondsPerMinute;
return (int) result;
}
private static int msFromTime(double t)
{
double result;
result = t % msPerSecond;
if (result < 0)
result += msPerSecond;
return (int) result;
}
private static double MakeTime(double hour, double min,
double sec, double ms)
{
return ((hour * MinutesPerHour + min) * SecondsPerMinute + sec)
* msPerSecond + ms;
}
private static double MakeDay(double year, double month, double date)
{
year += Math.floor(month / 12);
month = month % 12;
if (month < 0)
month += 12;
double yearday = Math.floor(TimeFromYear(year) / msPerDay);
double monthday = DayFromMonth((int)month, (int)year);
return yearday + monthday + date - 1;
}
private static double MakeDate(double day, double time)
{
return day * msPerDay + time;
}
private static double TimeClip(double d)
{
if (d != d ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY ||
Math.abs(d) > HalfTimeDomain)
{
return ScriptRuntime.NaN;
}
if (d > 0.0)
return Math.floor(d + 0.);
else
return Math.ceil(d + 0.);
}
/* end of ECMA helper functions */
/* find UTC time from given date... no 1900 correction! */
private static double date_msecFromDate(double year, double mon,
double mday, double hour,
double min, double sec,
double msec)
{
double day;
double time;
double result;
day = MakeDay(year, mon, mday);
time = MakeTime(hour, min, sec, msec);
result = MakeDate(day, time);
return result;
}
/* compute the time in msec (unclipped) from the given args */
private static final int MAXARGS = 7;
private static double date_msecFromArgs(Object[] args)
{
double array[] = new double[MAXARGS];
int loop;
double d;
for (loop = 0; loop < MAXARGS; loop++) {
if (loop < args.length) {
d = ScriptRuntime.toNumber(args[loop]);
if (d != d || Double.isInfinite(d)) {
return ScriptRuntime.NaN;
}
array[loop] = ScriptRuntime.toInteger(args[loop]);
} else {
if (loop == 2) {
array[loop] = 1; /* Default the date argument to 1. */
} else {
array[loop] = 0;
}
}
}
/* adjust 2-digit years into the 20th century */
if (array[0] >= 0 && array[0] <= 99)
array[0] += 1900;
return date_msecFromDate(array[0], array[1], array[2],
array[3], array[4], array[5], array[6]);
}
private static double jsStaticFunction_UTC(Object[] args)
{
return TimeClip(date_msecFromArgs(args));
}
/**
* 15.9.1.15 Date Time String Format
* Parse input string according to simplified ISO-8601 Extended Format:
*
YYYY-MM-DD'T'HH:mm:ss.sss'Z'YYYY-MM-DD'T'HH:mm:ss.sss[+-]hh:mm