Exemplo n.º 1
0
        public string ConvertToLocalizedString(DateTime?date, string format, DateLocalizationOptions options = null)
        {
            options = options ?? new DateLocalizationOptions();

            if (!date.HasValue)
            {
                return(options.NullText);
            }

            var dateValue = date.Value;
            var offset    = TimeSpan.Zero;

            if (options.EnableTimeZoneConversion)
            {
                dateValue = ConvertToSiteTimeZone(dateValue);
                offset    = CurrentTimeZone.GetUtcOffset(date.Value);
            }

            var parts = DateTimeParts.FromDateTime(dateValue, offset);

            if (options.EnableCalendarConversion && !(CurrentCalendar is GregorianCalendar))
            {
                parts = ConvertToSiteCalendar(dateValue, offset);
            }

            return(_dateFormatter.FormatDateTime(parts, format));
        }
 /// <summary>
 /// Loads the object from the data specified
 /// </summary>
 /// <param name="Data">Data to load into the object</param>
 protected override void LoadFromData(string Data)
 {
     foreach (Match TempMatch in Regex.Matches(Data, "(?<Title>[^\r\n:]+):(?<Value>[^\r\n]*)"))
     {
         if (TempMatch.Groups["Title"].Value.ToUpperInvariant() == "DTSTART")
         {
             StartTime = CurrentTimeZone.ToLocalTime(DateTime.Parse(TempMatch.Groups["Value"].Value.ToString(@"####/##/## ##:##")));
         }
         else if (TempMatch.Groups["Title"].Value.ToUpperInvariant() == "DTEND")
         {
             EndTime = CurrentTimeZone.ToLocalTime(DateTime.Parse(TempMatch.Groups["Value"].Value.ToString(@"####/##/## ##:##")));
         }
         else if (TempMatch.Groups["Title"].Value.ToUpperInvariant() == "LOCATION")
         {
             this.Location = TempMatch.Groups["Value"].Value;
         }
         else if (TempMatch.Groups["Title"].Value.ToUpperInvariant() == "SUMMARY;LANGUAGE=EN-US")
         {
             Subject = TempMatch.Groups["Value"].Value;
         }
         else if (TempMatch.Groups["Title"].Value.ToUpperInvariant() == "DESCRIPTION" && string.IsNullOrEmpty(Description))
         {
             Description = TempMatch.Groups["Value"].Value;
         }
     }
 }
        public async Task <IActionResult> Logout(string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            await _signInManager.SignOutAsync();

            var endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var utime   = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;

            System.DateTime startTime       = CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            DateTime        translateDate   = startTime.AddSeconds(utime);
            var             res             = _dbHelper.ExecSqlStoredProcedure("call login_time_length('" + translateDate.ToString("yyyy-MM-dd HH:mm:ss") + "'," + _user.Id + ",@s);");
            var             userOnLineTimes = "";

            if (res != null && res.Tables.Count > 0)
            {
                userOnLineTimes = res.Tables[0].Rows[0].ItemArray[0].ToString();
            }
            _memoryCache.Remove(_user.Name + "_" + _user.Id); //注销时移除client 连接id
            _logger.LogCustomerInfo($"{_user.Name} 注销登录,在线时长:{userOnLineTimes}", nameof(LoginAsync), nameof(AccountController), null);
            if (returnUrl != null)
            {
                return(LocalRedirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("HomePage", "Home"));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Returns the ICalendar item
        /// </summary>
        /// <returns>a string output of the ICalendar item</returns>
        public virtual string GetICalendar()
        {
            Contract.Requires <NullReferenceException>(!string.IsNullOrEmpty(Description), "Description");
            var FileOutput = new StringBuilder();

            FileOutput.AppendLine("BEGIN:VCALENDAR")
            .AppendLineFormat("METHOD:{0}", Cancel ? "CANCEL" : "REQUEST")
            .AppendLine("PRODID:-//Craigs Utility Library//EN")
            .AppendLine("VERSION:2.0")
            .AppendLine("BEGIN:VEVENT")
            .AppendLine("CLASS:PUBLIC")
            .AppendLineFormat("DTSTAMP:{0}", DateTime.Now.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
            .AppendLineFormat("CREATED:{0}", DateTime.Now.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
            .AppendLine(StripHTML(Description.Replace("<br />", System.Environment.NewLine)))
            .AppendLineFormat("DTStart:{0}", CurrentTimeZone.ToUniversalTime(StartTime).ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
            .AppendLineFormat("DTEnd:{0}", CurrentTimeZone.ToUniversalTime(EndTime).ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
            .AppendLineFormat("LOCATION:{0}", Location)
            .AppendLineFormat("SUMMARY;LANGUAGE=en-us:{0}", Subject)
            .AppendLineFormat("UID:{0}{1}{2}", CurrentTimeZone.ToUniversalTime(StartTime).ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture), CurrentTimeZone.ToUniversalTime(EndTime).ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture), Subject);
            if (AttendeeList.Count > 0)
            {
                FileOutput.AppendLineFormat("ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=\"{0}\":MAILTO:{0}", AttendeeList.ToString());
            }
            if (Organizer != null)
            {
                FileOutput.AppendLineFormat("ACTION;RSVP=TRUE;CN=\"{0}\":MAILTO:{0}\r\nORGANIZER;CN=\"{1}\":mailto:{0}", Organizer.Address, Organizer.DisplayName);
            }
            if (ContainsHTML(Description))
            {
                FileOutput.AppendLineFormat("X-ALT-DESC;FMTTYPE=text/html:{0}", Description.Replace("\n", ""));
            }
            else
            {
                FileOutput.AppendLineFormat("DESCRIPTION:{0}", Description);
            }
            return(FileOutput.AppendLine("SEQUENCE:1")
                   .AppendLine("PRIORITY:5")
                   .AppendLine("CLASS:")
                   .AppendLineFormat("LAST-MODIFIED:{0}", DateTime.Now.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
                   .AppendLine("STATUS:CONFIRMED")
                   .AppendLine("TRANSP:OPAQUE")
                   .AppendLineFormat("X-MICROSOFT-CDO-BUSYSTATUS:{0}", Status)
                   .AppendLine("X-MICROSOFT-CDO-INSTTYPE:0")
                   .AppendLine("X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY")
                   .AppendLine("X-MICROSOFT-CDO-ALLDAYEVENT:FALSE")
                   .AppendLine("X-MICROSOFT-CDO-IMPORTANCE:1")
                   .AppendLine("X-MICROSOFT-CDO-OWNERAPPTID:-1")
                   .AppendLineFormat("X-MICROSOFT-CDO-ATTENDEE-CRITICAL-CHANGE:{0}", DateTime.Now.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
                   .AppendLineFormat("X-MICROSOFT-CDO-OWNER-CRITICAL-CHANGE:{0}", DateTime.Now.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
                   .AppendLine("BEGIN:VALARM")
                   .AppendLine("TRIGGER;RELATED=START:-PT00H15M00S")
                   .AppendLine("ACTION:DISPLAY")
                   .AppendLine("DESCRIPTION:Reminder")
                   .AppendLine("END:VALARM")
                   .AppendLine("END:VEVENT")
                   .AppendLine("END:VCALENDAR")
                   .ToString());
        }
        /// <summary>
        /// Returns the local time that corresponds to a specified coordinated universal time (UTC).
        /// </summary>
        /// <param name="time">A UTC time.</param>
        /// <returns>
        /// A <see cref="T:System.DateTime"></see> instance whose value is the local time that corresponds to time.
        /// </returns>
        public override DateTime ToLocalTime(DateTime time)
        {
            if (time.Kind != DateTimeKind.Unspecified)
            {
                time = new DateTime(time.Ticks, DateTimeKind.Unspecified);
            }

            return(time.Add(CurrentTimeZone.GetUtcOffset(time) - GetUtcOffset(time)));
        }
Exemplo n.º 6
0
        /// <summary>
        /// 将本地时间转换为时间戳--毫秒级
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static long ToUnixTime(this DateTime date)
        {
            var startTime = CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区

            return(Convert.ToInt64((date - startTime).TotalSeconds * 1000));

            //var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            //return Convert.ToInt64((date - epoch).TotalSeconds * 1000);
        }
        /// <summary>
        /// Converts DateTime to the local time.
        /// </summary>
        /// <param name="time">The time.</param>
        /// <returns>Local DateTime</returns>
        public DateTime FromLocalTime(DateTime time)
        {
            if (time.Kind != DateTimeKind.Unspecified)
            {
                time = new DateTime(time.Ticks, DateTimeKind.Unspecified);
            }

            return(time.Add(GetUtcOffset(time) - CurrentTimeZone.GetUtcOffset(time)));
        }
Exemplo n.º 8
0
        /// <summary>
        /// 得到13位时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <param name="dateTimeKind"></param>
        /// <returns></returns>
        public static long GetTimeSpan(this DateTime?time, DateTimeKind dateTimeKind = DateTimeKind.Utc)
        {
            if (time == null)
            {
                time = DateTime.Now;
            }
            var  startTime = CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, dateTimeKind));
            long t         = (time.Value.Ticks - startTime.Ticks) / 10000; //除10000调整为13位

            return(t);
        }
        private DateTime ConvertLocalToUtc(int year,
                                           int month,
                                           int day,
                                           int hours        = 0,
                                           int minutes      = 0,
                                           int seconds      = 0,
                                           int milliseconds = 0
                                           )
        {
            var localDate  = new DateTime(year, month, day, hours, minutes, seconds, milliseconds, DateTimeKind.Unspecified);
            var offset     = CurrentTimeZone.GetUtcOffset(localDate);
            var withOffset = new DateTimeOffset(localDate, offset);

            return(withOffset.UtcDateTime);
        }
Exemplo n.º 10
0
 public virtual string GetVCalendar()
 {
     return(new StringBuilder().AppendLine("BEGIN:VCALENDAR")
            .AppendLine("VERSION:1.0")
            .AppendLine("BEGIN:VEVENT")
            .AppendLineFormat("DTStart:{0}", CurrentTimeZone.ToUniversalTime(StartTime).ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture))
            .AppendLineFormat("DTEnd:{0}", CurrentTimeZone.ToUniversalTime(EndTime).ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture))
            .AppendLineFormat("Location;ENCODING=QUOTED-PRINTABLE:{0}", Location)
            .AppendLineFormat("SUMMARY;ENCODING=QUOTED-PRINTABLE:{0}", Subject)
            .AppendLineFormat("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:{0}", Description)
            .AppendLineFormat("UID:{0}{1}{2}", CurrentTimeZone.ToUniversalTime(StartTime).ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture), CurrentTimeZone.ToUniversalTime(EndTime).ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture), Subject)
            .AppendLine("PRIORITY:3")
            .AppendLine("End:VEVENT")
            .AppendLine("End:VCALENDAR")
            .ToString());
 }
Exemplo n.º 11
0
        public string ConvertToLocalizedTimeString(DateTime?date, DateLocalizationOptions options = null)
        {
            options = options ?? new DateLocalizationOptions();

            if (!date.HasValue)
            {
                return(options.NullText);
            }

            var dateValue = date.Value;
            var offset    = TimeSpan.Zero;

            if (options.EnableTimeZoneConversion)
            {
                if (options.IgnoreDate)
                {
                    // The caller has asked us to ignore the date part. This usually because the source
                    // is a time-only field. In such cases (with an undefined date) it does not make sense
                    // to consider DST variations throughout the year, so we will use an arbitrary (but fixed)
                    // non-DST date for the conversion to ensure DST is never applied during conversion. The
                    // date part is usually DateTime.MinValue which we should not use because time zone
                    // conversion cannot wrap DateTime.MinValue around to the previous day, resulting in
                    // an undefined result. Instead we convert the date to a hard-coded date of 2000-01-01
                    // before the conversion, and back to the original date after.
                    var tempDate = new DateTime(2000, 1, 1, dateValue.Hour, dateValue.Minute, dateValue.Second, dateValue.Millisecond, dateValue.Kind);
                    tempDate  = ConvertToSiteTimeZone(tempDate);
                    dateValue = new DateTime(dateValue.Year, dateValue.Month, dateValue.Day, tempDate.Hour, tempDate.Minute, tempDate.Second, tempDate.Millisecond, tempDate.Kind);
                }
                else
                {
                    dateValue = ConvertToSiteTimeZone(dateValue);
                }

                offset = CurrentTimeZone.GetUtcOffset(date.Value);
            }

            var parts = DateTimeParts.FromDateTime(dateValue, offset);

            // INFO: No calendar conversion in this method - we expect the date component to be DateTime.MinValue and irrelevant anyway.

            return(_dateFormatter.FormatDateTime(parts, _dateTimeFormatProvider.LongTimeFormat));
        }
Exemplo n.º 12
0
        public string ConvertToLocalizedTimeString(DateTime?date, DateLocalizationOptions options = null)
        {
            options = options ?? new DateLocalizationOptions();

            if (!date.HasValue)
            {
                return(options.NullText);
            }

            var dateValue = date.Value;
            var offset    = TimeSpan.Zero;

            if (options.EnableTimeZoneConversion)
            {
                if (options.IgnoreDate)
                {
                    // The caller has asked us to ignore the date part and assume it is today. This usually because the source
                    // is a time-only field, in which case the date part is usually DateTime.MinValue which we should not use
                    // for the following reasons:
                    // * DST can be active or not dependeng on the time of the year. We want the conversion to always act as if the time represents today, but we don't want that date stored.
                    // * Time zone conversion cannot wrap DateTime.MinValue around to the previous day, resulting in undefined result.
                    // Therefore we convert the date to today's date before the conversion, and back to the original date after.
                    var today    = _clock.UtcNow.Date;
                    var tempDate = new DateTime(today.Year, today.Month, today.Day, dateValue.Hour, dateValue.Minute, dateValue.Second, dateValue.Millisecond, dateValue.Kind);
                    tempDate  = ConvertToSiteTimeZone(tempDate);
                    dateValue = new DateTime(dateValue.Year, dateValue.Month, dateValue.Day, tempDate.Hour, tempDate.Minute, tempDate.Second, tempDate.Millisecond, tempDate.Kind);
                }
                else
                {
                    dateValue = ConvertToSiteTimeZone(dateValue);
                }

                offset = CurrentTimeZone.GetUtcOffset(date.Value);
            }

            var parts = DateTimeParts.FromDateTime(dateValue, offset);

            // INFO: No calendar conversion in this method - we expect the date component to be DateTime.MinValue and irrelevant anyway.

            return(_dateFormatter.FormatDateTime(parts, _dateTimeFormatProvider.LongTimeFormat));
        }
Exemplo n.º 13
0
        /// <summary>
        /// 将本地时间转换为时间戳
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static double ToTimeStamp(this DateTime datetime)
        {
            var startTime = CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区

            return((datetime - startTime).TotalSeconds);
        }
Exemplo n.º 14
0
        /// <summary>
        ///     取时间戳生成随即数,替换交易单号中的后10位流水号
        /// </summary>
        /// <returns></returns>
        internal uint UnixStamp()
        {
            var ts = DateTime.Now - CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

            return(Convert.ToUInt32(ts.TotalSeconds));
        }
Exemplo n.º 15
0
 protected IQueryable <T> DatabaseCompareExpression(
     IQueryable <T> query,
     PropertyViewModel prop,
     string value,
     TimeZoneInfo timeZone)
 {
     if (prop.Type.IsDate)
     {
         // See if they just passed in a date or a date and a time
         DateTime parsedValue;
         if (DateTime.TryParse(value, out parsedValue))
         {
             // Correct offset.
             if (prop.Type.IsDateTimeOffset)
             {
                 DateTimeOffset dateTimeOffset = new DateTimeOffset(parsedValue, CurrentTimeZone.GetUtcOffset(parsedValue));
                 if (dateTimeOffset.TimeOfDay == TimeSpan.FromHours(0) &&
                     !value.Contains(':'))
                 {
                     // Only a date
                     var nextDate = dateTimeOffset.AddDays(1);
                     return(query.Where(string.Format(
                                            "{0} >= @0 && {0} < @1", prop.Name),
                                        dateTimeOffset, nextDate));
                 }
                 else
                 {
                     // Date and Time
                     return(query.Where(string.Format("{0} = @0",
                                                      prop.Name), dateTimeOffset));
                 }
             }
             else
             {
                 if (parsedValue.TimeOfDay == TimeSpan.FromHours(0) &&
                     !value.Contains(':'))
                 {
                     // Only a date
                     var nextDate = parsedValue.AddDays(1);
                     return(query.Where(string.Format(
                                            "{0} >= @0 && {0} < @1", prop.Name),
                                        parsedValue, nextDate));
                 }
                 else
                 {
                     // Date and Time
                     return(query.Where(string.Format("{0} = @0",
                                                      prop.Name), parsedValue));
                 }
             }
         }
         else
         {
             // Could not parse date string.
             return(null);
         }
     }
     else if (prop.Type.IsString)
     {
         if (value.Contains("*"))
         {
             return(query.Where($"{prop.Name}.StartsWith(\"{value.Replace("*", "")}\")"));
         }
         else
         {
             return(query.Where($"{prop.Name} = \"{value}\""));
         }
     }
     else if (prop.Type.IsEnum)
     {
         var expressions = new List <string>();
         foreach (var valuePart in value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
         {
             expressions.Add($"{prop.Name} = \"{prop.Type.EnumValues.SingleOrDefault(ev => ev.Key == Convert.ToInt32(valuePart)).Value}\"");
         }
         return(query.Where(string.Join(" || ", expressions)));
     }
     else
     {
         if (value.Contains(","))
         {
             var whereList = new List <string>();
             foreach (var num in value.Split(','))
             {
                 whereList.Add($"{prop.Name} = {num}");
             }
             return(query.Where(string.Join(" or ", whereList)));
         }
         else
         {
             return(query.Where(string.Format("{0} = {1}", prop.Name, value)));
         }
     }
 }
Exemplo n.º 16
0
        public static long ToTimeStamp(this DateTime dateTime)
        {
            var startTime = CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

            return((long)(dateTime - startTime).TotalMilliseconds);
        }
Exemplo n.º 17
0
        /// <summary>
        /// DateTime时间格式转换为10位不带毫秒的Unix时间戳
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <param name="dateTimeKind"></param>
        /// <returns>Unix时间戳格式</returns>
        public static int ConvertDateTimeInt(this DateTime time, DateTimeKind dateTimeKind = DateTimeKind.Utc)
        {
            DateTime startTime = CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, dateTimeKind));

            return((int)(time - startTime).TotalSeconds);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 将时间戳转换为本地时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime ToDateTimeByTimeStamp(this double timeStamp)
        {
            var startTime = CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区

            return(startTime.AddSeconds(timeStamp));
        }