Example #1
0
        public static DateTimeValue CreateNow(Context ctx)
        {
            var tz = PhpTimeZone.GetCurrentTimeZone(ctx);
            var dt = TimeZoneInfo.ConvertTimeFromUtc(System_DateTime.UtcNow, tz);

            return(new DateTimeValue(dt, tz));
        }
Example #2
0
        public static bool TryCreateFromFormat(Context ctx, string format, string?time, DateTimeZone?timezone, out DateTimeValue value)
        {
            // arguments

            // format: the time format string
            // time: given time value
            // timezone: timezone object or null, ignored when "time" specifies the timezone already

            // TODO: year offset

            var dateinfo = DateInfo.ParseFromFormat(format, time, out var errors);

            ctx.SetProperty <DateTimeErrors>(errors);

            if (errors != null && errors.HasErrors)
            {
                value = default;
                return(false);
            }

            var localtz   = timezone?._timezone ?? PhpTimeZone.GetCurrentTimeZone(ctx);
            var localdate = dateinfo.GetDateTime(System_DateTime.UtcNow, ref localtz);

            value = new DateTimeValue(localdate, localtz);
            return(true);
        }
Example #3
0
        protected DateTime(Context ctx)
        {
            Debug.Assert(ctx != null);

            _ctx = ctx;

            this.Time     = System_DateTime.UtcNow;
            this.TimeZone = PhpTimeZone.GetCurrentTimeZone(ctx);
        }
        public static DateTimeImmutable createFromFormat(Context ctx, string format, string time, DateTimeZone timezone = null)
        {
            // arguments
            var tz = (timezone != null) ? timezone._timezone : PhpTimeZone.GetCurrentTimeZone(ctx);

            var dateinfo = DateInfo.ParseFromFormat(format, time, out var errors);

            ctx.SetProperty <DateTimeErrors>(errors);

            if (errors != null && errors.HasErrors)
            {
                return(null);
            }

            return(new DateTimeImmutable(ctx, dateinfo.GetDateTime(ctx, System_DateTime.UtcNow), tz)); // TODO: dateinfo.TimeZones
        }
Example #5
0
        // public __construct ( string $timezone )
        public void __construct(string timezone_name)
        {
            if (timezone_name != null)
            {
                this.timezone = PhpTimeZone.GetTimeZone(timezone_name);

                if (this.timezone == null)
                {
                    //PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone", zoneName));
                    throw new ArgumentException();
                }
            }
            else
            {
                this.timezone = PhpTimeZone.GetCurrentTimeZone(_ctx);
            }
        }
Example #6
0
        // public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
        public void __construct(string time = null, DateTimeZone timezone = null)
        {
            this.TimeZone = (timezone == null)
                ? PhpTimeZone.GetCurrentTimeZone(_ctx)
                : timezone._timezone;

            if (TimeZone == null)
            {
                //PhpException.InvalidArgument("timezone");
                //return null;
                throw new ArgumentException();
            }

            this.Time = StrToTime(_ctx, time, System_DateTime.UtcNow);

            //this.date.Value = this.Time.ToString("yyyy-mm-dd HH:mm:ss");
            //this.timezone_type.Value = 3;
            //this.timezone.Value = TimeZone.Id;
        }
Example #7
0
        public static DateTimeValue CreateFromState(Context ctx, PhpArray array)
        {
            if (array == null || array.Count == 0)
            {
                return(CreateNow(ctx));
            }
            else
            {
                // resolve date/time
                var date = array.TryGetValue("date", out var dateval) && dateval.IsString(out var datestr)
                    ? System_DateTime.Parse(datestr, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal)
                    : System_DateTime.UtcNow;

                // resolve timezone or current
                var localtz = PhpTimeZone.GetCurrentTimeZone(ctx);

                if (array.TryGetValue("timezone", out var tzval) && tzval.IsString(out var tz) && tz.Length != 0)
                {
                    //if (array.TryGetValue("timezone_type", out var typeval) && typeval.IsLong(out var type) &&
                    //    type == 1 &&
                    //    DateInfo.TryParseTimeZoneOffset(tz, 0, out var tz_minutes))
                    //{
                    //    // UTC offset
                    //    localtz = DateInfo.ResolveTimeZone(tz_minutes);
                    //}
                    //else
                    {
                        // deals with any tz format
                        localtz = PhpTimeZone.GetTimeZone(tz) ?? throw new Spl.InvalidArgumentException($"timezone:'{tz}'");
                    }
                }

                //

                if (date.Kind == DateTimeKind.Utc)
                {
                    date = TimeZoneInfo.ConvertTimeFromUtc(date, localtz);
                }

                return(new DateTimeValue(date, localtz));
            }
        }
Example #8
0
        // public __construct ( string $timezone )
        public void __construct(Context ctx, string timezone_name)
        {
            if (timezone_name != null)
            {
                _timezone = PhpTimeZone.GetTimeZone(timezone_name);
                _name     = timezone_name;

                if (_timezone == null)
                {
                    // TODO: an offset value (+0200)

                    //PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone", timezone_name));
                    throw new Spl.InvalidArgumentException();
                }
            }
            else
            {
                _timezone = PhpTimeZone.GetCurrentTimeZone(ctx);
            }
        }
Example #9
0
        // public __construct ( string $timezone )
        public void __construct(Context ctx, string timezone_name)
        {
            if (timezone_name == null)
            {
                _timezone = PhpTimeZone.GetCurrentTimeZone(ctx);
            }
            else
            {
                var tz = PhpTimeZone.GetTimeZone(timezone_name);
                if (tz == null)
                {
                    PhpException.Throw(PhpError.Notice, Resources.LibResources.unknown_timezone, timezone_name);
                    throw new Spl.InvalidArgumentException();
                }

                //
                _timezone = tz;
                _name     = timezone_name;
            }
        }
Example #10
0
        public DateConfiguration()
        {
            Context.RegisterConfiguration(this);

            Register <DateConfiguration>("date.timezone", ExtensionName,
                                         (config) => config.TimeZoneInfo?.Id ?? string.Empty, // TODO: this is not PHP name
                                         (config, value) =>
            {
                if (value.IsString(out var zoneName))
                {
                    var zone = PhpTimeZone.GetTimeZone(zoneName);
                    if (zone != null)
                    {
                        config.TimeZoneInfo = zone;
                    }
                    else
                    {
                        PhpException.Throw(PhpError.Notice, Resources.LibResources.unknown_timezone, zoneName);
                    }
                }
Example #11
0
        // public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
        public DateTimeImmutable(Context ctx, string time = null, DateTimeZone timezone = null)
        {
            Debug.Assert(ctx != null);

            this.TimeZone = (timezone == null)
                ? PhpTimeZone.GetCurrentTimeZone(ctx)
                : timezone._timezone;

            if (TimeZone == null)
            {
                //PhpException.InvalidArgument("timezone");
                //return null;
                throw new ArgumentException();
            }

            this.Time = DateTime.StrToTime(ctx, time, System_DateTime.UtcNow);

            //this.date.Value = this.Time.ToString("yyyy-mm-dd HH:mm:ss");
            //this.timezone_type.Value = 3;
            //this.timezone.Value = TimeZone.Id;
        }
Example #12
0
        public static DateTimeValue Parse(Context ctx, string timestr, TimeZoneInfo?timezone)
        {
            Debug.Assert(ctx != null);
            Debug.Assert(timestr != null);

            //
            ctx !.SetProperty(DateTimeErrors.Empty);

            timestr = timestr != null?timestr.Trim() : string.Empty;

            var localtz = timezone ?? PhpTimeZone.GetCurrentTimeZone(ctx);

            Debug.Assert(localtz != null);

            System_DateTime localdate;

            //
            if (timestr.Length == 0 || timestr.EqualsOrdinalIgnoreCase(DateTimeValue.Now))
            {
                // most common case
                localdate = TimeZoneInfo.ConvertTimeFromUtc(System_DateTime.UtcNow, localtz);
            }
            else
            {
                var result = DateInfo.Parse(timestr, System_DateTime.UtcNow, ref localtz, out var error);
                if (error != null)
                {
                    ctx.SetProperty <DateTimeErrors>(new DateTimeErrors {
                        Errors = new[] { error }
                    });
                    throw new Spl.Exception(error);
                }

                localdate = result;
            }

            //
            return(new DateTimeValue(localdate, localtz));
        }
Example #13
0
        public DateTime(Context ctx, string time, DateTimeZone timezone)
        {
            Debug.Assert(ctx != null);

            _ctx = ctx;

            if (timezone == null)
            {
                TimeZone = PhpTimeZone.GetCurrentTimeZone(ctx);
            }
            else
            {
                //var datetimezone = timezone as DateTimeZone;
                //if (datetimezone == null)
                //{
                //    PhpException.InvalidArgumentType("timezone", "DateTimeZone");
                //    TimeZone = PhpTimeZone.CurrentTimeZone;
                //}
                //else
                {
                    TimeZone = timezone.timezone;
                }
            }

            if (TimeZone == null)
            {
                //PhpException.InvalidArgument("timezone");
                //return null;
                throw new ArgumentException();
            }

            this.Time = StrToTime(ctx, time, System_DateTime.UtcNow);

            //this.date.Value = this.Time.ToString("yyyy-mm-dd HH:mm:ss");
            //this.timezone_type.Value = 3;
            //this.timezone.Value = TimeZone.Id;
        }
Example #14
0
        public static DateTime createFromFormat(Context ctx, string format, string time, DateTimeZone timezone = null)
        {
            // arguments
            var tz = (timezone != null) ? timezone._timezone : PhpTimeZone.GetCurrentTimeZone(ctx);

            if (format == null)
            {
                //PhpException.InvalidArgument("format");
                //return false;
                throw new ArgumentNullException();
            }

            if (time == null)
            {
                //PhpException.InvalidArgument("time");
                //return false;
                throw new ArgumentNullException();
            }

            if (format == "U")
            {
                long seconds = 0;
                if (Int64.TryParse(time, out seconds))
                {
                    DateTimeOffset offset = DateTimeOffset.FromUnixTimeSeconds(seconds);
                    return(new DateTime(ctx)
                    {
                        Time = offset.UtcDateTime,
                        // TODO should be set as UTC ?
                        TimeZone = TimeZoneInfo.Utc
                    });
                }
                else
                {
                    throw new ArgumentException("The time argument could not be parsed as an integer.");
                }
            }

            var builder = new StringBuilder();

            //used to replace 24 hour H character with 12 hour format h if needed
            bool twelveHour = false;

            //flag to reset the datetime to base Unix DateTime (1.1.1970)
            //bool resetUnixDateTime = false;

            // create DateTime from format+time
            for (int i = 0; i < format.Length; i++)
            {
                var c = format[i];

                switch (c)
                {
                case 'd':
                case 'j':
                    builder.Append("dd");
                    break;

                case 'D':
                case 'l':
                    builder.Append("ddd");
                    break;

                case 'F':
                case 'M':
                    builder.Append("MMM");
                    break;

                case 'm':
                case 'n':
                    builder.Append("MM");
                    break;

                case 'Y':
                    builder.Append("yyyy");
                    break;

                case 'a':
                case 'A':
                    builder.Append("tt");
                    twelveHour = true;
                    break;

                case 'g':
                case 'G':
                case 'h':
                case 'H':
                    builder.Append("HH");
                    break;

                case 'i':
                    builder.Append("mm");
                    break;

                case 's':
                    builder.Append("ss");
                    break;

                case '!':
                //resetUnixDateTime = true;
                //throw new NotImplementedException("Unix time resetting is not implemented.");
                case '?':
                case '/':
                case '*':
                case '+':
                case '#':
                case 'U':
                case 'S':
                case 'z':
                case 'e':
                case 'O':
                case 'P':
                case 'T':
                    throw new NotImplementedException($"Format modifier '{c}' at position {i}.");

                default:
                    builder.Append(c);
                    break;
                }
            }

            if (twelveHour)
            {
                builder.Replace('H', 'h');
            }

            var csStyleFormat = builder.ToString();

            var success = System_DateTime.TryParseExact(time, csStyleFormat, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out var dateTime);

            if (success)
            {
                return(new DateTime(ctx)
                {
                    Time = dateTime
                });
            }
            else
            {
                throw new NotImplementedException("Given datetime format string is not supported or it is invalid.");
            }
        }
Example #15
0
 //public static array listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )
 public static PhpArray listIdentifiers(int what = DateTimeZone.ALL, string country = null) => PhpTimeZone.timezone_identifiers_list(what, country);
Example #16
0
 /// <summary>
 /// Returns associative array containing dst, offset and the timezone name.
 /// </summary>
 public static PhpArray listAbbreviations() => PhpTimeZone.timezone_abbreviations_list();
Example #17
0
        public static DateTime createFromFormat(Context ctx, string format, string time, DateTimeZone timezone = null)
        {
            // arguments
            var tz = (timezone != null) ? timezone.timezone : PhpTimeZone.GetCurrentTimeZone(ctx);

            if (format == null)
            {
                //PhpException.InvalidArgument("format");
                //return false;
                throw new ArgumentNullException();
            }

            if (time == null)
            {
                //PhpException.InvalidArgument("time");
                //return false;
                throw new ArgumentNullException();
            }

            // create DateTime from format+time
            int i = 0;  // position in <timestr>

            foreach (var c in format)
            {
                switch (c)
                {
                //case 'd':
                //case 'j':
                //    var day = PHP.Library.StrToTime.DateInfo.ParseUnsignedInt(timestr, ref i, 2);
                //    // ... use day
                //    break;
                //case 'F':
                //case 'M':
                //    // parse  ...
                //    break;
                default:
                    if (i < time.Length && time[i] == c)
                    {
                        // match
                        i++;
                    }
                    else
                    {
                        // not match
                        //PhpException.InvalidArgument("time");   // time not matching format
                        //return false;
                        throw new ArgumentException();
                    }
                    break;
                }
            }

            if (i < time.Length)
            {
                //PhpException.InvalidArgument("time");   // time not matching format
                //return false;
                throw new ArgumentException();
            }

            ////
            //return new __PHP__DateTime(context, true)
            //{
            //     //Time = new DateTime(year, month, day, hour, minute, second, millisecond),
            //     TimeZone = tz,
            //};

            throw new NotImplementedException();
        }
Example #18
0
        public System.DateTime GetDateTime(Context ctx, System.DateTime utcStart)
        {
            var zone  = PhpTimeZone.GetCurrentTimeZone(ctx);
            var start = TimeZoneInfo.ConvertTime(utcStart, TimeZoneInfo.Utc, zone);// zone.ToLocalTime(utcStart);

            // following operates on local time defined by the parsed info or by the current time zone //

            if (have_date > 0 && have_time == 0)
            {
                h = 0;
                i = 0;
                s = 0;
            }
            else
            {
                if (h == -1)
                {
                    h = start.Hour;
                }
                if (i == -1)
                {
                    i = start.Minute;
                }
                if (s == -1)
                {
                    s = start.Second;
                }
            }

            if (y == -1)
            {
                y = start.Year;
            }
            if (m == -1)
            {
                m = start.Month;
            }
            else if (m == 0)
            {
                m = 1; --relative.m;
            }
            if (d == -1)
            {
                d = start.Day;
            }
            else if (d == 0)
            {
                d = 1; --relative.d;
            }

            int days_overflow;

            CheckOverflows(y, m, ref d, ref h, out days_overflow);

            var result = new System.DateTime(y, m, d, h, i, s, DateTimeKind.Unspecified);

            result = result.AddDays(relative.d + days_overflow);
            result = result.AddMonths(relative.m);
            result = result.AddYears(relative.y);
            result = result.AddHours(relative.h);
            result = result.AddMinutes(relative.i);
            result = result.AddSeconds(relative.s);

            // adds relative weekday:
            if (have_weekday_relative > 0)
            {
                int dow        = (int)result.DayOfWeek;
                int difference = relative.weekday - dow;

                if ((relative.d < 0 && difference < 0) || (relative.d >= 0 && difference <= -relative.weekday_behavior))
                {
                    difference += 7;
                }

                if (relative.weekday >= 0)
                {
                    result = result.AddDays(difference);
                }
                else
                {
                    result = result.AddDays(dow - relative.weekday - 7);
                }
            }

            // convert to UTC:
            if (have_zone > 0)
            {
                result = result.AddMinutes(-z);
            }
            else
            {
                if (zone.IsInvalidTime(result))
                {
                    // We ended up in an invalid time. This time was skipped because of day-light saving change.
                    // Figure out the direction we were moving, and step in the direction until the next valid time.
                    int secondsStep = ((result - utcStart).Ticks >= 0) ? 1 : -1;
                    do
                    {
                        result = result.AddSeconds(secondsStep);
                    }while (zone.IsInvalidTime(result));
                }

                result = TimeZoneInfo.ConvertTime(result, zone, TimeZoneInfo.Utc);// zone.ToUniversalTime(result);
            }

            //
            return(result);
        }
 protected DateTime(Context ctx)
     : this(ctx, System_DateTime.UtcNow, PhpTimeZone.GetCurrentTimeZone(ctx))
 {
 }