Beispiel #1
0
 private Options(bool pretty = false, bool excludeNulls = false, bool jsonp = false, DateTimeFormat dateFormat = DateTimeFormat.NewtonsoftStyleMillisecondsSinceUnixEpoch)
 {
     ShouldPrettyPrint = pretty;
     ShouldExcludeNulls = excludeNulls;
     IsJSONP = jsonp;
     UseDateTimeFormat = dateFormat;
 }
Beispiel #2
0
 /// <summary>
 /// Configuration for Jil serialization options.
 /// 
 /// Available options:
 ///   prettyPrint - whether or not to include whitespace and newlines for ease of reading
 ///   excludeNulls - whether or not to write object members whose value is null
 ///   jsonp - whether or not the serialized json should be valid for use with JSONP
 ///   dateFormat - the style in which to serialize DateTimes
 ///   includeInherited - whether or not to serialize members declared by an objects base types
 ///   allowHashFunction - whether or not Jil should try to use hashes instead of strings when deserializing object members, malicious content may be able to force member collisions if this is enabled
 /// </summary>
 public Options(bool prettyPrint = false, bool excludeNulls = false, bool jsonp = false, DateTimeFormat dateFormat = DateTimeFormat.NewtonsoftStyleMillisecondsSinceUnixEpoch, bool includeInherited = false, bool allowHashFunction = true)
 {
     ShouldPrettyPrint = prettyPrint;
     ShouldExcludeNulls = excludeNulls;
     IsJSONP = jsonp;
     UseDateTimeFormat = dateFormat;
     ShouldIncludeInherited = includeInherited;
     AllowHashFunction = allowHashFunction;
 }
 public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
     : base(serializer, serializer.MaxItemsInObjectGraph,
         new StreamingContext(StreamingContextStates.All),
         serializer.IgnoreExtensionDataObject)
 {
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
     this.dataContractSurrogate = serializer.DataContractSurrogate;
     this.dateTimeFormat = serializer.DateTimeFormat;
     this.useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
 }
    /// <summary>
    /// Format objectDateTime according to the format enum. "[error]" if the value is invalid.
    /// </summary>
    /// <param name="dateTimeInstance">
    /// The yaf date time.
    /// </param>
    /// <param name="format">
    /// The format.
    /// </param>
    /// <param name="objectDateTime">
    /// The object date time.
    /// </param>
    /// <returns>
    /// Formatted datetime or "[error]" if invalid.
    /// </returns>
    public static string Format([NotNull] this IDateTime dateTimeInstance, DateTimeFormat format, [NotNull] object objectDateTime)
    {
      CodeContracts.VerifyNotNull(dateTimeInstance, "dateTimeInstance");
      CodeContracts.VerifyNotNull(objectDateTime, "objectDateTime");

      try
      {
        DateTime dateTime = Convert.ToDateTime(objectDateTime);

        switch (format)
        {
          case DateTimeFormat.BothDateShort:
            return dateTimeInstance.FormatDateTimeShort(dateTime);

          case DateTimeFormat.BothTopic:
            return dateTimeInstance.FormatDateTimeTopic(dateTime);

          case DateTimeFormat.DateLong:
            return dateTimeInstance.FormatDateLong(dateTime);

          case DateTimeFormat.DateShort:
            return dateTimeInstance.FormatDateShort(dateTime);

          case DateTimeFormat.Time:
            return dateTimeInstance.FormatTime(dateTime);
          
          case DateTimeFormat.Both:
          default:
            return dateTimeInstance.FormatDateTime(dateTime);

        }
      }
      catch
      {
      }

      // failed convert...
      return "[error]";
    }
Beispiel #5
0
        /// <summary>Converts the given DateTime value to a string using the given summary desired format</summary>
        /// <param name="dt">Specifies the DateTime value to convert</param>
        /// <param name="dtFormat">Specifies the desired format from the set of supported enum values.</param>
        /// <returns>The DateTime converted to a string based on the desired format.</returns>
        public static string CvtToString(ref DateTime dt, DateTimeFormat dtFormat)
        {
            string result = string.Empty;

            switch (dtFormat)
            {
                default:
                case DateTimeFormat.LogDefault:
                    result = Fcns.CheckedFormat("{0}-{1}-{2} {3}:{4}:{5}.{6}",
                                                    dt.Year.ToString("D4"), dt.Month.ToString("D2"), dt.Day.ToString("D2"),
                                                    dt.Hour.ToString("D2"), dt.Minute.ToString("D2"), dt.Second.ToString("D2"),
                                                    dt.Millisecond.ToString("D3"));
                    break;
                case DateTimeFormat.ShortWithMSec:
                    result = Fcns.CheckedFormat("{0}{1}{2}_{3}{4}{5}.{6}",
                                                    dt.Year.ToString("D4"), dt.Month.ToString("D2"), dt.Day.ToString("D2"),
                                                    dt.Hour.ToString("D2"), dt.Minute.ToString("D2"), dt.Second.ToString("D2"),
                                                    dt.Millisecond.ToString("D3"));
                    break;
            }

            return result;
        }
Beispiel #6
0
 /// <summary>
 /// Tries to find time within the passed string and return it as DateTime structure. 
 /// It recognizes only time while ignoring date, so date in the returned DateTime is always 1/1/1.
 /// </summary>
 /// <param name="str">string that contains time</param>
 /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
 /// <param name="time">parsed time output</param>
 /// <returns>true if time was found, else false</returns>
 public static bool TryParseTime(string str, DateTimeFormat default_format, out System.DateTime time)
 {
     lock (lock_variable)
     {
         ParsedDateTime parsed_time;
         if (!TryParseTime(str, default_format, out parsed_time, null))
         {
             time = new System.DateTime(1, 1, 1);
             return false;
         }
         time = parsed_time.DateTime;
         return true;
     }
 }
Beispiel #7
0
 /// <summary>
 /// Converts datetime to string per portal
 /// </summary>
 public abstract string DateTimeToString(DateTime dt,
     DateTimeFormat format = DateTimeFormat.LongDateTime,
     ISession session = null);
Beispiel #8
0
 /// <summary>
 /// Tries to find date within the passed string and return it as DateTime structure. 
 /// It recognizes only date while ignoring time, so time in the returned DateTime is always 0:0:0.
 /// If year of the date was not found then it accepts the current year. 
 /// </summary>
 /// <param name="str">string that contains date</param>
 /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
 /// <param name="date">parsed date output</param>
 /// <returns>true if date was found, else false</returns>
 public static bool TryParseDate(string str, DateTimeFormat default_format, out System.DateTime date)
 {
     lock (lock_variable)
     {
         ParsedDateTime parsed_date;
         if (!TryParseDate(str, default_format, out parsed_date))
         {
             date = new System.DateTime(1, 1, 1);
             return false;
         }
         date = parsed_date.DateTime;
         return true;
     }
 }
 private static extern int dialog_set_notification_start_date_format_elapsed(IntPtr dialog, DateTimeFormat elapsed_format);
Beispiel #10
0
        /// <summary>
        /// Configuration for Jil serialization options.
        /// 
        /// Available options:
        ///   prettyPrint - whether or not to include whitespace and newlines for ease of reading
        ///   excludeNulls - whether or not to write object members whose value is null
        ///   jsonp - whether or not the serialized json should be valid for use with JSONP
        ///   dateFormat - the style in which to serialize DateTimes and TimeSpans
        ///   includeInherited - whether or not to serialize members declared by an objects base types
        ///   unspecifiedDateTimeKindBehavior - how to treat DateTime's with a DateTimeKind of Unspecified (Jil converts all DateTimes to Utc for serialization, use DateTimeOffset to preserve time zone information)
        ///   serializationNameFormat - how to serialize names of properties/objects unless specified explicitly by an attribute
        /// </summary>
        public Options(bool prettyPrint = false, bool excludeNulls = false, bool jsonp = false, DateTimeFormat dateFormat = DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch, bool includeInherited = false, UnspecifiedDateTimeKindBehavior unspecifiedDateTimeKindBehavior = UnspecifiedDateTimeKindBehavior.IsLocal, SerializationNameFormat serializationNameFormat = SerializationNameFormat.Verbatim)
        {
            ShouldPrettyPrint = prettyPrint;
            ShouldExcludeNulls = excludeNulls;
            IsJSONP = jsonp;

#pragma warning disable 618
            // upgrade from the obsolete DateTimeFormat enumeration; warning disabled to allow it, but all other references
            //  should be expunged
            if (dateFormat == DateTimeFormat.NewtonsoftStyleMillisecondsSinceUnixEpoch)
            {
                dateFormat = DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch;
            }
#pragma warning restore 618

            UseDateTimeFormat = dateFormat;
            ShouldIncludeInherited = includeInherited;
            UseUnspecifiedDateTimeKindBehavior = unspecifiedDateTimeKindBehavior;
            SerializationNameFormat = serializationNameFormat;
        }
 /// <summary>
 /// Tries to find time within the passed string and return it as DateTime structure. 
 /// It recognizes only time while ignoring date, so date in the returned DateTime is always 1/1/1.
 /// </summary>
 /// <param name="str">string that contains time</param>
 /// <param name="default_format">format to be used preferably in ambivalent instances</param>
 /// <param name="time">parsed time output</param>
 /// <returns>true if time was found, else false</returns>
 public static bool TryParseTime(this string str, DateTimeFormat default_format, out DateTime time)
 {
     ParsedDateTime parsed_time;
     if (!TryParseTime(str, default_format, out parsed_time, null))
     {
         time = new DateTime(1, 1, 1);
         return false;
     }
     time = parsed_time.DateTime;
     return true;
 }
 public override String ToString()
 {
     return(DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo));
 }
 public override string ToString()
 {
     return(DateTimeFormat.Format(ClockDateTime, null, null, Offset));
 }
 public string ToString(string format)
 {
     return(DateTimeFormat.Format(ClockDateTime, format, null, Offset));
 }
Beispiel #15
0
 public string ToString(string format)
 {
     return(DateTimeFormat.Format(this.ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, this.Offset));
 }
Beispiel #16
0
 public string ToString(string format, IFormatProvider formatProvider)
 {
     return(DateTimeFormat.Format(this.ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), this.Offset));
 }
Beispiel #17
0
 public override string ToString()
 {
     return(DateTimeFormat.Format(this.ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, this.Offset));
 }
Beispiel #18
0
 public string ToString(string?format) =>
 DateTimeFormat.Format(ClockDateTime, format, null, Offset);
 public String ToString(String format)
 {
     return(DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo));
 }
        /// <summary>
        /// Tries to find date within the passed string and return it as ParsedDateTime object. 
        /// It recognizes only date while ignoring time, so time in the returned ParsedDateTime is always 0:0:0.
        /// If year of the date was not found then it accepts the current year. 
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format to be used preferably in ambivalent instances</param>
        /// <param name="parsed_date">parsed date output</param>
        /// <returns>true if date was found, else false</returns>
        public static bool TryParseDate(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_date)
        {
            parsed_date = null;

            if (string.IsNullOrEmpty(str))
                return false;

            //look for dd/mm/yy
            Match m = Regex.Match(str, @"(?<=^|[^\d])(?'day'\d{1,2})\s*(?'separator'[\\/\.])+\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'year'\d{2}|\d{4})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                DateTime date;
                if ((default_format ^ DateTimeFormat.USA_DATE) == DateTimeFormat.USA_DATE)
                {
                    if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["day"].Value), int.Parse(m.Groups["month"].Value), out date))
                        return false;
                }
                else
                {
                    if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                        return false;
                }
                parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                return true;
            }

            //look for [yy]yy-mm-dd
            m = Regex.Match(str, @"(?<=^|[^\d])(?'year'\d{2}|\d{4})\s*(?'separator'[\-])\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'day'\d{1,2})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                DateTime date;
                if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                    return false;
                parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                return true;
            }

            //look for month dd yyyy
            m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th|-?rd|-?nd)?\s*,?\s*(?'year'\d{4})(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (!m.Success)
                //look for dd month [yy]yy
                m = Regex.Match(str, @"(?:^|[^\d\w:])(?'day'\d{1,2})(?:-?st\s+|-?th\s+|-?rd\s+|-?nd\s+|-|\s+)(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*(?:\s*,?\s*|-)'?(?'year'\d{2}|\d{4})(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (!m.Success)
                //look for yyyy month dd
                m = Regex.Match(str, @"(?:^|[^\d\w])(?'year'\d{4})\s+(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th|-?rd|-?nd)?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (!m.Success)
                //look for month dd hh:mm:ss MDT|UTC yyyy
                m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})\s+\d{2}\:\d{2}\:\d{2}\s+(?:MDT|UTC)\s+(?'year'\d{4})(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (!m.Success)
                //look for  month dd [yyyy]
                m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th|-?rd|-?nd)?(?:\s*,?\s*(?'year'\d{4}))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                int month = -1;
                int index_of_date = m.Index;
                int length_of_date = m.Length;

                switch (m.Groups["month"].Value)
                {
                    case "Jan":
                    case "JAN":
                        month = 1;
                        break;
                    case "Feb":
                    case "FEB":
                        month = 2;
                        break;
                    case "Mar":
                    case "MAR":
                        month = 3;
                        break;
                    case "Apr":
                    case "APR":
                        month = 4;
                        break;
                    case "May":
                    case "MAY":
                        month = 5;
                        break;
                    case "Jun":
                    case "JUN":
                        month = 6;
                        break;
                    case "Jul":
                        month = 7;
                        break;
                    case "Aug":
                    case "AUG":
                        month = 8;
                        break;
                    case "Sep":
                    case "SEP":
                        month = 9;
                        break;
                    case "Oct":
                    case "OCT":
                        month = 10;
                        break;
                    case "Nov":
                    case "NOV":
                        month = 11;
                        break;
                    case "Dec":
                    case "DEC":
                        month = 12;
                        break;
                }

                int year;
                if (!string.IsNullOrEmpty(m.Groups["year"].Value))
                    year = int.Parse(m.Groups["year"].Value);
                else
                    year = DefaultDate.Year;

                DateTime date;
                if (!convert_to_date(year, month, int.Parse(m.Groups["day"].Value), out date))
                    return false;
                parsed_date = new ParsedDateTime(index_of_date, length_of_date, -1, -1, date);
                return true;
            }

            return false;
        }
 public string ToString(string format, IFormatProvider formatProvider)
 {
     return(DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset));
 }
        /// <summary>
        /// Tries to find date and/or time within the passed string and return it as ParsedDateTime object. 
        /// If only date was found, time in the returned ParsedDateTime is always 0:0:0.
        /// If only time was found, date in the returned ParsedDateTime is DefaultDate.
        /// </summary>
        /// <param name="str">string that contains date-time</param>
        /// <param name="default_format">format to be used preferably in ambivalent instances</param>
        /// <param name="parsed_date_time">parsed date-time output</param>
        /// <returns>true if date or time was found, else false</returns>
        public static bool TryParseDateOrTime(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
        {
            parsed_date_time = null;

            ParsedDateTime parsed_date;
            ParsedDateTime parsed_time;
            if (!TryParseDate(str, default_format, out parsed_date))
            {
                if (!TryParseTime(str, default_format, out parsed_time, null))
                    return false;

                DateTime date_time = new DateTime(DefaultDate.Year, DefaultDate.Month, DefaultDate.Day, parsed_time.DateTime.Hour, parsed_time.DateTime.Minute, parsed_time.DateTime.Second);
                parsed_date_time = new ParsedDateTime(-1, -1, parsed_time.IndexOfTime, parsed_time.LengthOfTime, date_time, parsed_time.UtcOffset);
            }
            else
            {
                if (!TryParseTime(str, default_format, out parsed_time, parsed_date))
                {
                    DateTime date_time = new DateTime(parsed_date.DateTime.Year, parsed_date.DateTime.Month, parsed_date.DateTime.Day, 0, 0, 0);
                    parsed_date_time = new ParsedDateTime(parsed_date.IndexOfDate, parsed_date.LengthOfDate, -1, -1, date_time);
                }
                else
                {
                    DateTime date_time = new DateTime(parsed_date.DateTime.Year, parsed_date.DateTime.Month, parsed_date.DateTime.Day, parsed_time.DateTime.Hour, parsed_time.DateTime.Minute, parsed_time.DateTime.Second);
                    parsed_date_time = new ParsedDateTime(parsed_date.IndexOfDate, parsed_date.LengthOfDate, parsed_time.IndexOfTime, parsed_time.LengthOfTime, date_time, parsed_time.UtcOffset);
                }
            }

            return true;
        }
 public bool TryFormat(Span <char> destination, out int charsWritten, ReadOnlySpan <char> format = default, IFormatProvider formatProvider = null) =>
 DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, formatProvider, Offset);
        /// <summary>
        /// Tries to find time within the passed string (relatively to the passed parsed_date if any) and return it as ParsedDateTime object.
        /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format to be used preferably in ambivalent instances</param>
        /// <param name="parsed_time">parsed date-time output</param>
        /// <param name="parsed_date">ParsedDateTime object if the date was found within this string, else NULL</param>
        /// <returns>true if time was found, else false</returns>
        public static bool TryParseTime(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_time, ParsedDateTime parsed_date)
        {
            parsed_time = null;

            string time_zone_r;
            if (default_format == DateTimeFormat.USA_DATE)
                time_zone_r = @"(?:\s*(?'time_zone'UTC|GMT|CST|EST))?";
            else
                time_zone_r = @"(?:\s*(?'time_zone'UTC|GMT))?";

            Match m;
            if (parsed_date != null && parsed_date.IndexOfDate > -1)
            {//look around the found date
                //look for <date> hh:mm:ss <UTC offset>
                m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{2})\s*:\s*(?'minute'\d{2})\s*:\s*(?'second'\d{2})\s+(?'offset_sign'[\+\-])(?'offset_hh'\d{2}):?(?'offset_mm'\d{2})(?=$|[^\d\w])", RegexOptions.Compiled);
                if (!m.Success)
                    //look for <date> [h]h:mm[:ss] [PM/AM] [UTC/GMT]
                    m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[^\d\w])", RegexOptions.Compiled);
                if (!m.Success)
                    //look for [h]h:mm:ss [PM/AM] [UTC/GMT] <date>
                    m = Regex.Match(str.Substring(0, parsed_date.IndexOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[\s,]+)", RegexOptions.Compiled);
                if (!m.Success)
                    //look for [h]h:mm:ss [PM/AM] [UTC/GMT] within <date>
                    m = Regex.Match(str.Substring(parsed_date.IndexOfDate, parsed_date.LengthOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[\s,]+)", RegexOptions.Compiled);
            }
            else//look anywhere within string
            {
                //look for hh:mm:ss <UTC offset>
                m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{2})\s*:\s*(?'minute'\d{2})\s*:\s*(?'second'\d{2})\s+(?'offset_sign'[\+\-])(?'offset_hh'\d{2}):?(?'offset_mm'\d{2})?(?=$|[^\d\w])", RegexOptions.Compiled);
                if (!m.Success)
                    //look for [h]h:mm[:ss] [PM/AM] [UTC/GMT]
                    m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[^\d\w])", RegexOptions.Compiled);
            }

            if (!m.Success)
                return false;

            //try
            //{
            int hour = int.Parse(m.Groups["hour"].Value);
            if (hour < 0 || hour > 23)
                return false;

            int minute = int.Parse(m.Groups["minute"].Value);
            if (minute < 0 || minute > 59)
                return false;

            int second = 0;
            if (!string.IsNullOrEmpty(m.Groups["second"].Value))
            {
                second = int.Parse(m.Groups["second"].Value);
                if (second < 0 || second > 59)
                    return false;
            }

            if (string.Compare(m.Groups["ampm"].Value, "PM", true) == 0 && hour < 12)
                hour += 12;
            else if (string.Compare(m.Groups["ampm"].Value, "AM", true) == 0 && hour == 12)
                hour -= 12;

            DateTime date_time = new DateTime(1, 1, 1, hour, minute, second);

            if (m.Groups["offset_hh"].Success)
            {
                int offset_hh = int.Parse(m.Groups["offset_hh"].Value);
                int offset_mm = 0;
                if (m.Groups["offset_mm"].Success)
                    offset_mm = int.Parse(m.Groups["offset_mm"].Value);
                TimeSpan utc_offset = new TimeSpan(offset_hh, offset_mm, 0);
                if (m.Groups["offset_sign"].Value == "-")
                    utc_offset = -utc_offset;
                parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time, utc_offset);
                return true;
            }

            if (m.Groups["time_zone"].Success)
            {
                TimeSpan utc_offset;
                switch (m.Groups["time_zone"].Value)
                {
                    case "UTC":
                    case "GMT":
                        utc_offset = new TimeSpan(0, 0, 0);
                        break;
                    case "CST":
                        utc_offset = new TimeSpan(-6, 0, 0);
                        break;
                    case "EST":
                        utc_offset = new TimeSpan(-5, 0, 0);
                        break;
                    default:
                        throw new Exception("Time zone: " + m.Groups["time_zone"].Value + " is not defined.");
                }
                parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time, utc_offset);
                return true;
            }

            parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time);
            //}
            //catch(Exception e)
            //{
            //    return false;
            //}
            return true;
        }
Beispiel #25
0
 public override string ToString() =>
 DateTimeFormat.Format(ClockDateTime, null, null, Offset);
 private static extern int dialog_set_notification_start_date_format(IntPtr dialog, DateTimeFormat date_format, DateTimeFormat time_format, DateTimeFormat week_format);
Beispiel #27
0
 public string ToString([StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string?format) =>
 DateTimeFormat.Format(ClockDateTime, format, null, Offset);
Beispiel #28
0
 /// <summary>
 /// For compatibility with earlier Jil versions.
 /// 
 /// Configuration for Jil serialization options.
 /// 
 /// Available options:
 ///   prettyPrint - whether or not to include whitespace and newlines for ease of reading
 ///   excludeNulls - whether or not to write object members whose value is null
 ///   jsonp - whether or not the serialized json should be valid for use with JSONP
 ///   dateFormat - the style in which to serialize DateTimes and TimeSpans
 ///   includeInherited - whether or not to serialize members declared by an objects base types
 ///   unspecifiedDateTimeKindBehavior - how to treat DateTime's with a DateTimeKind of Unspecified (Jil converts all DateTimes to Utc for serialization, use DateTimeOffset to preserve time zone information)
 /// </summary>
 public Options(bool prettyPrint, bool excludeNulls, bool jsonp, DateTimeFormat dateFormat, bool includeInherited, UnspecifiedDateTimeKindBehavior unspecifiedDateTimeKindBehavior) :
     this(prettyPrint, excludeNulls, jsonp, dateFormat, includeInherited, unspecifiedDateTimeKindBehavior, SerializationNameFormat.Verbatim)
 { }
Beispiel #29
0
 public string ToString(IFormatProvider?formatProvider) =>
 DateTimeFormat.Format(ClockDateTime, null, formatProvider, Offset);
 /// <summary>
 /// 日期格式化为一定的格式
 /// </summary>
 /// <param name="datetime"></param>
 /// <returns></returns>
 public static string Format(System.DateTime datetime, DateTimeFormat format)
 {           
     return datetime.ToString(_formatArray[(int)(format)]);
 }
Beispiel #31
0
 public string ToString([StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string?format, IFormatProvider?formatProvider) =>
 DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset);
Beispiel #32
0
 public String ToString(String format)
 {
     Contract.Ensures(Contract.Result <String>() != null);
     return(DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset));
 }
Beispiel #33
0
 public bool TryFormat(Span <char> destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] ReadOnlySpan <char> format = default, IFormatProvider?formatProvider = null) =>
 DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, formatProvider, Offset);
Beispiel #34
0
        /// <summary>
        /// Tries to find date and time within the passed string and return it as ParsedDateTime object. 
        /// </summary>
        /// <param name="str">string that contains date-time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_date_time">parsed date-time output</param>
        /// <returns>true if both date and time were found, else false</returns>
        public static bool TryParseDateTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
        {
            lock (lock_variable)
            {
                if (DateTimeHelper.TryParse(str, DateTimeHelper.DateTimeFormat.USA_DATE, out parsed_date_time)
                    && parsed_date_time.IsDateFound
                    && parsed_date_time.IsTimeFound
                    )
                    return true;

                parsed_date_time = null;
                return false;
            }
        }
Beispiel #35
0
 public String ToString(String format)
 {
     return(DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset));
 }
Beispiel #36
0
        /// <summary>
        /// Tries to find time within the passed string (relatively to the passed parsed_date if any) and return it as ParsedDateTime object.
        /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_time">parsed date-time output</param>
        /// <param name="parsed_date">ParsedDateTime object if the date was found within this string, else NULL</param>
        /// <returns>true if time was found, else false</returns>
        public static bool TryParseTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_time, ParsedDateTime parsed_date)
        {
            lock (lock_variable)
            {
                parsed_time = null;

                Match m;
                if (parsed_date != null && parsed_date.IndexOfDate > -1)
                {//look around the found date
                    //look for <date> [h]h:mm[:ss] [PM/AM]
                    m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    if (!m.Success)
                        //look for [h]h:mm:ss <date>
                        m = Regex.Match(str.Substring(0, parsed_date.IndexOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[\s,]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                else//look anywere within string
                    //look for [h]h:mm[:ss] [PM/AM]
                    m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                if (m.Success)
                {
                    try
                    {
                        int hour = int.Parse(m.Groups["hour"].Value);
                        if (hour < 0 || hour > 23)
                            return false;

                        int minute = int.Parse(m.Groups["minute"].Value);
                        if (minute < 0 || minute > 59)
                            return false;

                        int second = 0;
                        if (!string.IsNullOrEmpty(m.Groups["second"].Value))
                        {
                            second = int.Parse(m.Groups["second"].Value);
                            if (second < 0 || second > 59)
                                return false;
                        }

                        if (string.Compare(m.Groups[4].Value, "PM", true) > -1)
                            hour += 12;

                        System.DateTime date_time = new System.DateTime(1, 1, 1, hour, minute, second);
                        parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time);
                    }
                    catch
                    {
                        return false;
                    }
                    return true;
                }

                return false;
            }
        }
Beispiel #37
0
 public String ToString(String format, IFormatProvider formatProvider)
 {
     Contract.Ensures(Contract.Result <String>() != null);
     return(DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset));
 }
 /// <summary>
 /// Tries to find date and/or time within the passed string and return it as DateTime structure. 
 /// If only date was found, time in the returned DateTime is always 0:0:0.
 /// If only time was found, date in the returned DateTime is DefaultDate.
 /// </summary>
 /// <param name="str">string that contains date and(or) time</param>
 /// <param name="default_format">format to be used preferably in ambivalent instances</param>
 /// <param name="date_time">parsed date-time output</param>
 /// <returns>true if date and/or time was found, else false</returns>
 public static bool TryParseDateOrTime(this string str, DateTimeFormat default_format, out DateTime date_time)
 {
     ParsedDateTime parsed_date_time;
     if (!TryParseDateOrTime(str, default_format, out parsed_date_time))
     {
         date_time = new DateTime(1, 1, 1);
         return false;
     }
     date_time = parsed_date_time.DateTime;
     return true;
 }
        public JsonSerializer(DateTimeFormat dateTimeFormat = DateTimeFormat.Default)
		{
            DateFormat = dateTimeFormat;
		}
        /// <summary>
        /// Tries to find date and time within the passed string and return it as ParsedDateTime object. 
        /// </summary>
        /// <param name="str">string that contains date-time</param>
        /// <param name="default_format">format to be used preferably in ambivalent instances</param>
        /// <param name="parsed_date_time">parsed date-time output</param>
        /// <returns>true if both date and time were found, else false</returns>
        public static bool TryParseDateTime(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
        {
            if (DateTimeRoutines.TryParseDateOrTime(str, default_format, out parsed_date_time)
                && parsed_date_time.IsDateFound
                && parsed_date_time.IsTimeFound
                )
                return true;

            parsed_date_time = null;
            return false;
        }
        /// <summary>
        /// Convert an IDictionary to a JSON string.
        /// </summary>
        /// <param name="dictionary">The value to convert.</param>
        /// <returns>The JSON object as a string or null when the value type is not supported.</returns>
        protected static string SerializeIDictionary(IDictionary dictionary, DateTimeFormat dateTimeFormat = DateTimeFormat.Default)
        {
            StringBuilder result = new StringBuilder("{");

            foreach (DictionaryEntry entry in dictionary)
            {
                if (result.Length > 1)
                {
                    result.Append(",");
                }

                result.Append("\"" + entry.Key + "\"");
                result.Append(":");
                result.Append(SerializeObject(entry.Value, dateTimeFormat));
            }

            result.Append("}");
            return result.ToString();
        }
 /// <summary>
 /// Tries to find time within the passed string and return it as ParsedDateTime object. 
 /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
 /// </summary>
 /// <param name="str">string that contains date-time</param>
 /// <param name="default_format">format to be used preferably in ambivalent instances</param>
 /// <param name="parsed_time">parsed date-time output</param>
 /// <returns>true if time was found, else false</returns>
 public static bool TryParseTime(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_time)
 {
     return TryParseTime(str, default_format, out parsed_time, null);
 }
Beispiel #43
0
 public override String ToString()
 {
     Contract.Ensures(Contract.Result <String>() != null);
     return(DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset));
 }
 public static AttributeMetadata CreateDateTime(DateTimeFormat? format = DateTimeFormat.DateOnly, ImeMode? mode = ImeMode.Auto, string formulaDefinition = null)
 {
     return new DateTimeAttributeMetadata
     {
         Format = format,
         ImeMode = mode,
         FormulaDefinition = formulaDefinition
     };
 }
Beispiel #45
0
 public String ToString(String format, IFormatProvider formatProvider)
 {
     return(DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset));
 }
Beispiel #46
0
 /// <summary>Converts the given DateTime value to a string using the given summary desired format</summary>
 /// <param name="dt">Specifies the DateTime value to convert</param>
 /// <param name="dtFormat">Specifies the desired format from the set of supported enum values.</param>
 /// <returns>The DateTime converted to a string based on the desired format.</returns>
 public static string CvtToString(DateTime dt, DateTimeFormat dtFormat)
 {
     return CvtToString(ref dt, dtFormat);
 }
 public bool SetStartDateTime(DateTime dateTime, DateTimeFormat date, DateTimeFormat time, DateTimeFormat week = DateTimeFormat.None)
 {
     if (dialog_set_notification_start_date_format(handle, date, time, week) != BPS.BPS_SUCCESS &&
         dialog_set_notification_start_date_time(handle, (long)(dateTime.ToUniversalTime() - GetEpoch()).TotalMilliseconds) != BPS.BPS_SUCCESS)
     {
         return false;
     }
     return UpdateDialog(false);
 }
        /// <summary>
        /// Convert an IEnumerable to a JSON string.
        /// </summary>
        /// <param name="enumerable">The value to convert.</param>
        /// <returns>The JSON object as a string or null when the value type is not supported.</returns>
        protected static string SerializeIEnumerable(IEnumerable enumerable, DateTimeFormat dateTimeFormat = DateTimeFormat.Default)
        {
            StringBuilder result = new StringBuilder("[");

            foreach (object current in enumerable)
            {
                if (result.Length > 1)
                {
                    result.Append(",");
                }

                result.Append(SerializeObject(current, dateTimeFormat));
            }

            result.Append("]");
            return result.ToString();
        }
 public bool SetStartElapsedTime(TimeSpan timeSpan, DateTimeFormat format)
 {
     if (dialog_set_notification_start_date_format_elapsed(handle, format) != BPS.BPS_SUCCESS &&
         dialog_set_notification_start_date_time(handle, (long)timeSpan.TotalMilliseconds) != BPS.BPS_SUCCESS)
     {
         return false;
     }
     return UpdateDialog(false);
 }
        /// <summary>
        /// Convert an object to a JSON string.
        /// </summary>
        /// <param name="o">The value to convert. Supported types are: Boolean, String, Byte, (U)Int16, (U)Int32, Float, Double, Decimal, Array, IDictionary, IEnumerable, Guid, Datetime, DictionaryEntry, Object and null.</param>
        /// <returns>The JSON object as a string or null when the value type is not supported.</returns>
        /// <remarks>For objects, only public properties with getters are converted.</remarks>
        public static string SerializeObject(object o, DateTimeFormat dateTimeFormat = DateTimeFormat.Default)
        {
            if (o == null)
                return "null";

            Type type = o.GetType();

            switch (type.Name)
            {
                case "Boolean":
                    {
                        return (bool)o ? "true" : "false";
                    }
                case "String":
                case "Char":
                case "Guid":
                    {
                        return "\"" + SerializeString(o as String) + "\"";
                    }
                case "Single":
                case "Double":
                case "Decimal":
                case "Float":
                case "Byte":
                case "SByte":
                case "Int16":
                case "UInt16":
                case "Int32":
                case "UInt32":
                case "Int64":
                case "UInt64":
                    {
                        return o.ToString();
                    }
                case "DateTime":
                    {
                        switch (dateTimeFormat)
                        {
                            case DateTimeFormat.Ajax:
                                // This MSDN page describes the problem with JSON dates:
                                // http://msdn.microsoft.com/en-us/library/bb299886.aspx
                                return "\"" + DateTimeExtensions.ToASPNetAjax((DateTime)o) + "\"";
                            case DateTimeFormat.ISO8601:
                            case DateTimeFormat.Default:
                            default:
                                return "\"" + DateTimeExtensions.ToIso8601((DateTime)o) + "\"";
                        }
                    }
            }

            if (o is IDictionary && !type.IsArray)
            {
                IDictionary dictionary = o as IDictionary;
                return SerializeIDictionary(dictionary, dateTimeFormat);
            }

            if (o is IEnumerable)
            {
                IEnumerable enumerable = o as IEnumerable;
                return SerializeIEnumerable(enumerable, dateTimeFormat);
            }
//
//            if (type == typeof(System.Collections.DictionaryEntry))
//            {
//                DictionaryEntry entry = o as DictionaryEntry;
//                Hashtable hashtable = new Hashtable();
//                hashtable.Add(entry.Key, entry.Value);
//                return SerializeIDictionary(hashtable, dateTimeFormat);
//            }

            if (type.IsClass)
            {
                Hashtable hashtable = new Hashtable();

                // Iterate through all of the methods, looking for public GET properties
                MethodInfo[] methods = type.GetMethods();
                foreach (MethodInfo method in methods)
                {
                    // We care only about property getters when serializing
                    if (method.Name.StartsWith("get_"))
                    {
                        // Ignore abstract and virtual objects
                        if (method.IsAbstract)
                        {
                            continue;
                        }

                        // Ignore delegates and MethodInfos
                        if ((method.ReturnType == typeof(System.Delegate)) ||
                            (method.ReturnType == typeof(System.MulticastDelegate)) ||
                            (method.ReturnType == typeof(System.Reflection.MethodInfo)))
                        {
                            continue;
                        }
                        // Ditto for DeclaringType
                        if ((method.DeclaringType == typeof(System.Delegate)) ||
                            (method.DeclaringType == typeof(System.MulticastDelegate)))
                        {
                            continue;
                        }

                        object returnObject = method.Invoke(o, null);
                        hashtable.Add(method.Name.Substring(4), returnObject);                 
                    }
                }
                return SerializeIDictionary(hashtable, dateTimeFormat);
            }

            return null;
        }
Beispiel #51
0
 public bool TryFormat(Span <char> destination, out int charsWritten, string format = null, IFormatProvider formatProvider = null) =>
 DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);