예제 #1
0
파일: Aggregator.cs 프로젝트: adambird/eaep
        public int[] Count(string query, DateTime rangeFrom, DateTime rangeTo, int timeSlices, string groupBy)
        {
            int[] result = new int[timeSlices];

            TimeSpan rangeDuration = rangeTo.Subtract(rangeFrom);
            int timeSliceDuration = (int)rangeDuration.TotalMilliseconds / timeSlices;

            for (int timeSlice = 0; timeSlice < timeSlices; timeSlice++)
            {
                EAEPMessages messages = store.GetMessages(
                    rangeFrom.AddMilliseconds(timeSlice * timeSliceDuration),
                    rangeFrom.AddMilliseconds((timeSlice + 1) * timeSliceDuration),
                    query);

                if (groupBy != null)
                {
                    HashSet<string> groups = new HashSet<string>();

                    foreach (EAEPMessage message in messages)
                    {
                        if (message.ContainsParameter(groupBy) && !groups.Contains(message[groupBy]))
                        {
                            groups.Add(message[groupBy]);
                        }
                    }

                    result[timeSlice] = groups.Count;
                }
                else
                {
                    result[timeSlice] = messages.Count;
                }
            }
            return result;
        }
예제 #2
0
		public IAdaptingType read( FlashorbBinaryReader reader, ParseContext parseContext )
		{
            double dateTime = reader.ReadDouble();
            // ignore the stupid timezone
            reader.ReadUnsignedShort();

            DateTime sent = new DateTime( 1970, 1, 1 );

#if (FULL_BUILD || PURE_CLIENT_LIB )
            // get the offset of the time zone the server is in
            double localTimezoneOffset = TimeZone.CurrentTimeZone.GetUtcOffset( sent ).TotalMilliseconds;
            // convert 1/1/1970 12AM to UTC
            sent = TimeZone.CurrentTimeZone.ToUniversalTime( sent );
#else
            double localTimezoneOffset = TimeZoneInfo.Local.GetUtcOffset( sent ).TotalMilliseconds;
            sent = TimeZoneInfo.ConvertTime( sent, TimeZoneInfo.Utc );
#endif
            
            // bring it back to 12AM
            sent = sent.AddMilliseconds( localTimezoneOffset );

            // now that the sent object is in UTC and it represents 1/1/1970 12AM
            // convert it to the time sent by the client. The result of the operation
            // is going to be client's datetime object in UTC
            sent = sent.AddMilliseconds( dateTime );

            return new DateType( sent );
		}	
예제 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AccountInfo cu = ServerImpl.Instance.GetCurrentUser(Context);
            if (cu == null || !cu.IsAdmin) throw new Exception("你没有权限访问该页面!");

            if (IsPostBack)
            {
                switch (Request.Params["command"])
                {
                case "Delete":
                    {
                        Core.MessageImpl.Instance.DeleteMessages(Request.Params["data"]);
                        break;
                    }
                }
            }

            DateTime from, to, baseDate = new DateTime(1900, 1, 1);

            from = Request.QueryString["From"] == null ? new DateTime(1900, 1, 1) : baseDate.AddMilliseconds(Convert.ToInt32(Request.QueryString["From"]));
            to = Request.QueryString["To"] == null ? new DateTime(2100, 1, 1) : baseDate.AddMilliseconds(Convert.ToInt32(Request.QueryString["To"]));

            Int32 pageSize = 15;
            Int32 user = Request.QueryString["User"] == null ? 0 : Convert.ToInt32(Request.QueryString["User"]);
            Int32 peer = Request.QueryString["Peer"] == null ? 0 : Convert.ToInt32(Request.QueryString["Peer"]);
            int msgId = 0;
            if (Request.QueryString["CurrentPage"] != null)
            {
                _currentPage = Convert.ToInt32(Request.QueryString["CurrentPage"]);
                msgId = 0;
            }
            else
            {
                _currentPage = -1;
                msgId = Request.QueryString["MsgID"] == null ? 0 : Convert.ToInt32(Request.QueryString["MsgID"]);
            }

            Core.MessageImpl.Instance.WriteCache();

            DataTable msgs = null;
            if (peer > 0) msgs = Core.MessageImpl.Instance.GetUserMessages(user, peer, from, to, pageSize, ref _currentPage, out _pageCount, msgId);
            else msgs = Core.MessageImpl.Instance.GetGroupMessages(user, from, to, pageSize, ref _currentPage, out _pageCount, msgId);

            foreach (DataRow row in msgs.Rows)
            {
                Message_MessageCtrl ctrl = LoadControl("MessageCtrl.ascx") as Message_MessageCtrl;
                ctrl.Data = row;
                FindControl("MsgContainer").Controls.Add(ctrl);
            }
        }
        public void TestGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = new DateTime(2005, 6, 1, 9, 30, 17);

            // Test yearly
            NthIncludedDayTrigger yearlyTrigger = new NthIncludedDayTrigger();
            yearlyTrigger.IntervalType = NthIncludedDayTrigger.IntervalTypeYearly;
            yearlyTrigger.StartTimeUtc = startCalendar;
            yearlyTrigger.N = 10;
            yearlyTrigger.FireAtTime = "14:35:15";

            DateTimeOffset targetCalendar = new DateTime(2006, 1, 10, 14, 35, 15).ToUniversalTime();
            DateTimeOffset? nextFireTimeUtc;

            nextFireTimeUtc = yearlyTrigger.GetFireTimeAfter(startCalendar.AddMilliseconds(1000));
            Assert.AreEqual(targetCalendar, nextFireTimeUtc.Value);

            // Test monthly
            NthIncludedDayTrigger monthlyTrigger = new NthIncludedDayTrigger();
            monthlyTrigger.IntervalType = NthIncludedDayTrigger.IntervalTypeMonthly;
            monthlyTrigger.StartTimeUtc = startCalendar;
            monthlyTrigger.N = 5;
            monthlyTrigger.FireAtTime = "14:35:15";

            targetCalendar = new DateTime(2005, 6, 5, 14, 35, 15).ToUniversalTime();
            nextFireTimeUtc = monthlyTrigger.GetFireTimeAfter(startCalendar.AddMilliseconds(1000));
            Assert.AreEqual(targetCalendar, nextFireTimeUtc.Value);

            // Test weekly
            NthIncludedDayTrigger weeklyTrigger = new NthIncludedDayTrigger();
            weeklyTrigger.IntervalType = NthIncludedDayTrigger.IntervalTypeWeekly;
            weeklyTrigger.StartTimeUtc = startCalendar;
            weeklyTrigger.N = 3;
            weeklyTrigger.FireAtTime = "14:35:15";

            //roll start date forward to first day of the next week
            while (startCalendar.DayOfWeek != DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek)
            {
                startCalendar = startCalendar.AddDays(1);
            }

            //calculate expected fire date
            targetCalendar = new DateTime(startCalendar.Year, startCalendar.Month, startCalendar.Day, 14, 35, 15);

            //first day of the week counts as one. add two more to get N=3.
            targetCalendar = targetCalendar.AddDays(2);

            nextFireTimeUtc = weeklyTrigger.GetFireTimeAfter(startCalendar.AddMilliseconds(1000));
            Assert.AreEqual(targetCalendar.ToUniversalTime(), nextFireTimeUtc.Value);
        }
예제 #5
0
파일: JRow.cs 프로젝트: Yabko/jUtils
 private static DateTime convertUnixTimeStampToDateTime(double unixTimeStamp)
 {
     // Unix timestamp is seconds past epoch
     System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
     dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
     return dtDateTime;
 }
        private static DateTime ToDateTime(long timeStr)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(timeStr);

            return(dt);
        }
예제 #7
0
        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        public static DateTime GetTimeByJavascript(long jsTimeStamp)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(jsTimeStamp);

            return(dt);
        }
        public List<OrdenesPagoDetalleDto> Listado(string sortBy, string sortDirection, DateTime fechaDesde, DateTime fechaHasta, 
                bool? conAnulados, int pageIndex, int pageSize, out int pageTotal)
        {
            var criteros = new PagingCriteria();

            fechaDesde = fechaDesde.AddMilliseconds(-1);
            fechaHasta = fechaHasta.AddDays(1);
            criteros.PageNumber = pageIndex;
            criteros.PageSize = pageSize;
            criteros.SortBy = !string.IsNullOrEmpty(sortBy) ? sortBy : "FechaPago";
            criteros.SortDirection = !string.IsNullOrEmpty(sortDirection) ? sortDirection : "ASC";

            Expression<Func<OrdenesPagoDetalle, bool>> where = x => (x.ImportePagado.Value == 0) &&
                                                                    (!conAnulados.HasValue || x.FechaAnulacion.HasValue == conAnulados) &&
                                                                    (x.FechaPago.Value > fechaDesde && x.FechaPago.Value < fechaHasta);
           
            var resultados = Uow.OrdenesPagosDetalle.Listado(criteros,
                                                     where,
                                                     x => x.OrdenesPago,
                                                     x => x.SucursalAlta);
            

            pageTotal = resultados.PagedMetadata.TotalItemCount;

            return resultados.Entities.Project().To<OrdenesPagoDetalleDto>().ToList();   
        }
예제 #9
0
 private DateTime nextTriggeringTime(DateTime input, long increment)
 {
     DateTime output;
     switch (_periodicityType)
     {
         case PeriodicityType.TOP_OF_MILLISECOND:
             output = new DateTime(input.Year, input.Month, input.Day, input.Hour, input.Minute, input.Second, input.Millisecond);
             output = output.AddMilliseconds(increment);
             return output;
         case PeriodicityType.TOP_OF_SECOND:
             output = new DateTime(input.Year, input.Month, input.Day, input.Hour, input.Minute, input.Second);
             output = output.AddSeconds(increment);
             return output;
         case PeriodicityType.TOP_OF_MINUTE:
             output = new DateTime(input.Year, input.Month, input.Day, input.Hour, input.Minute, 0);
             output = output.AddMinutes(increment);
             return output;
         case PeriodicityType.TOP_OF_HOUR:
             output = new DateTime(input.Year, input.Month, input.Day, input.Hour, 0, 0);
             output = output.AddHours(increment);
             return output;
         case PeriodicityType.TOP_OF_DAY:
             output = new DateTime(input.Year, input.Month, input.Day);
             output = output.AddDays(increment);
             return output;
         default:
             throw new Exception("invalid periodicity type: " + _periodicityType);
     }
 }
예제 #10
0
        /// <summary>
        /// 将 Unix时间戳格式 转换为DateTime时间格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>long</returns>
        public static DateTime ConvertDateTimeToInt(long time)
        {
            System.DateTime Time     = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            DateTime        dateTime = Time.AddMilliseconds(time);

            return(dateTime);
        }
예제 #11
0
        public static DateTime TimeStampToDateTime(long timeStamp)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            DateTime        dt        = startTime.AddMilliseconds(timeStamp);

            return(dt);
        }
예제 #12
0
 public static System.DateTime FromUnixTime(double p_unixTimeStamp)
 {
     System.DateTime time      = System.DateTime.MinValue;
     System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
     time = startTime.AddMilliseconds(p_unixTimeStamp);
     return(time);
 }
예제 #13
0
 public static DateTime ConvertFromUnixTimeStamp(double unixTimeStamp)
 {
     // Unix timestamp is seconds past epoch
     DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
     dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToUniversalTime();
     return dtDateTime;
 }
예제 #14
0
 public static System.DateTime ToDateFromUtc(this double utc)
 {
     //return new DateTime(1970, 1, 1, 0, 0, 0).AddMinutes((DateTime.Now - DateTime.UtcNow).TotalMinutes).AddMilliseconds(utc);
     System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
     dtDateTime = dtDateTime.AddMilliseconds(utc).ToLocalTime();
     return(dtDateTime);
 }
예제 #15
0
        public object History()
        {
            var token = HttpContext.Current.Request.Form["Api_Token"];
            int id    = db.MarketerUsers.Where(p => p.Api_Token == token).FirstOrDefault().Id;

            var query = db.MarketerFactor.Where(p => p.Status == 0 || p.Status == 2).Where(p => p.MarketerUser.Id == id);
            var sdate = HttpContext.Current.Request.Form["StartDate"];
            var edate = HttpContext.Current.Request.Form["EndDate"];



            if (sdate != null)
            {
                System.DateTime sdateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
                sdateTime = sdateTime.AddMilliseconds(Convert.ToInt64(sdate));

                query = query.Where(p => p.Date >= sdateTime);
            }
            if (edate != null)
            {
                System.DateTime edateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
                edateTime = edateTime.AddMilliseconds(Convert.ToInt64(edate));

                query = query.Where(p => p.Date <= edateTime);
            }
            var data = query.Select(p => new { p.Id, p.Date, p.Buyer, p.BuyerAddress, p.BuyerMobile, p.BuyerPhoneNumber, p.BuyerPostalCode, p.Status, p.TotalPrice }).OrderByDescending(p => p.Id);

            return(new
            {
                Message = 0,
                Data = new PagedItem <object>(data, "")
            });
        }
예제 #16
0
        public static DateTime UnixTimeConverter(double unx)
        {
            DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dateTime = dateTime.AddMilliseconds(unx).ToLocalTime();

            return dateTime;
        }
예제 #17
0
        public bool ProcessNewsData(string jstr)
        {
            JObject jnlst = JObject.Parse(jstr);

            Console.WriteLine("//////////////////////////////////////////");
            Console.WriteLine(jnlst["results"].GetType());
            Console.WriteLine("//////////////////////////////////////////");
            bool res = false;

            foreach (var news in jnlst["results"])
            {
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                // 当地时区
                double   time = (double)news["pubDate"];
                DateTime dt   = startTime.AddMilliseconds(time);
                //Console.WriteLine(dt.ToString("yyyy/MM/dd"));
                string date  = dt.ToString("yyyy/MM/dd");
                string url   = (string)news["sourceUrl"];
                string title = (string)news["title"];
                Console.WriteLine(date + " " + url + " " + title);
                Console.ReadLine();
                NewsData     nd  = new NewsData(date, url, title);//date,url,title
                INewsDataBLL ndb = new NewsDataBLL();
                res = ndb.insert(nd);
            }

            //Console.WriteLine(jnlst["results"]);
            //Console.ReadLine();
            return(res);
        }
예제 #18
0
   private static DateTime ExtractDate( string input, string pattern, CultureInfo culture )
   {
      DateTime dt = DateTime.MinValue;
      var regex = new Regex( pattern );
      if ( regex.IsMatch( input ) )
      {
         var matches = regex.Matches( input );
         var match = matches[0];
         var ms = Convert.ToInt64( match.Groups[1].Value );
         var epoch = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc );
         dt = epoch.AddMilliseconds( ms );

         // adjust if time zone modifier present
         if ( match.Groups.Count > 2 && !String.IsNullOrEmpty( match.Groups[3].Value ) )
         {
            var mod = DateTime.ParseExact( match.Groups[3].Value, "HHmm", culture );
            if ( match.Groups[2].Value == "+" )
            {
               dt = dt.Add( mod.TimeOfDay );
            }
            else
            {
               dt = dt.Subtract( mod.TimeOfDay );
            }
         }

      }
      return dt;
   }
		public async Task EntityConverter_ConvertObjectToJson_ForCreating_Succeeds()
		{
			// Test if objects is converted to json correctly
			var dateTimeEpoc = new DateTime(1970, 1, 1, 0, 0, 0, 0);

			#region Client Object and Json
			
			var simpleEntity = new SimpleEntity()
			{
				Code = "123",
				Description = "FOO",
				Id = new Guid("53697fab-137f-4242-b710-0139886b50f4"),
				StartDate = dateTimeEpoc.AddMilliseconds(1387188617287),
				EndDate = null,
				Boolean = true,
				NullableBoolean = null,				
				Integer = 5,
				NullableInteger = null
			};

			const string expected = "{\"Code\":\"123\",\"Description\":\"FOO\",\"Id\":\"53697fab-137f-4242-b710-0139886b50f4\",\"StartDate\":\"2013-12-16T10:10:17.287\",\"EndDate\":null,\"Boolean\":true,\"NullableBoolean\":null,\"Integer\":5,\"NullableInteger\":null}";
			#endregion

			var converter = new EntityConverter();
			string result = await converter.ConvertObjectToJsonAsync(simpleEntity, null);
			
			Assert.AreEqual(expected, result);
		}
예제 #20
0
파일: Picasa.cs 프로젝트: Sleeckx/Jamie
        private static DateTime FromUnixTimeStamp(ulong unixTimeStamp)
        {
            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();

            return dtDateTime;
        }
        public static DateTime ToDateTime(string dt)
        {

            if (dt.StartsWith("/DateISO"))
            {
                int i = dt.IndexOf('(');
                dt = dt.Substring(i + 1);
                i = dt.LastIndexOf(')');
                dt = dt.Substring(0, i);
                var d = DateTime.Parse(dt, null, System.Globalization.DateTimeStyles.RoundtripKind);
                return d;
            }
            dt = dt.Substring(6);
            dt = dt.Substring(0, dt.Length - 2);
            if (dt.StartsWith("-"))
            {

            }
            int z = dt.LastIndexOfAny(new[] { '+', '-' });
            if (z > 0)
                dt = dt.Substring(0, dt.Length - z + 1);
            //long ticks = long.Parse(dt) * 10000L + DatetimeMinTimeTicks;
            //return new DateTime(ticks, DateTimeKind.Utc);

            var date = new DateTime(1970, 1, 1);
            date = date.AddMilliseconds(long.Parse(dt));
            return date;
        }
예제 #22
0
        public static List <AttendanceListRecordResponse> GetAttendanceList(string access_token, string param)
        {
            List <AttendanceListRecordResponse> attendanceListRecordResponse = new List <AttendanceListRecordResponse>();
            string  tagUrl  = "https://oapi.dingtalk.com/attendance/listRecord?access_token=" + access_token + "";
            string  result  = HttpHelper.Post(tagUrl, param);
            JObject jObject = JObject.Parse(result);
            JToken  jToken  = jObject["recordresult"];


            if (jToken == null)
            {
                return(attendanceListRecordResponse);
            }
            foreach (var jp in jToken)
            {
                AttendanceListRecordResponse temp = new AttendanceListRecordResponse();
                temp.userId      = jp["userId"].ToString();
                temp.userAddress = jp["userAddress"] == null ? string.Empty : jp["userAddress"].ToString();
                System.DateTime time      = System.DateTime.MinValue;
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                time = startTime.AddMilliseconds(Convert.ToDouble(jp["userCheckTime"]));
                temp.userCheckTime = time.ToString();
                attendanceListRecordResponse.Add(temp);
            }

            //var attendanceListRecordResponse = JsonConvert.DeserializeObject<AttendanceListRecordResponse>(jToken.ToString());
            return(attendanceListRecordResponse);
        }
예제 #23
0
        public static string formatTimestamp(long timestamp)
        {
            DateTime date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

            date = date.AddMilliseconds(timestamp);
            return(date.ToLocalTime().ToString("T"));
        }
예제 #24
0
        public override NodeResult Check()
        {
            DateTime end;

            nextUpdate = DateTime.Now;
            nextUpdate = nextUpdate.AddMilliseconds(1000 - nextUpdate.Millisecond);

            if (timeout.Value == TimeSpan.MaxValue)
                end = DateTime.MaxValue;
            else
                end = DateTime.Now + timeout.Value;

            while (true)
            {
                DateTime now = DateTime.Now;

                if (now < nextUpdate)
                {
                    Thread.Sleep(500);
                    continue;
                }
                if (now > end)
                    return NodeResult.Skip;

                if (year.Value.Check(nextUpdate.Year) && month.Value.Check(nextUpdate.Month) && day.Value.Check(nextUpdate.Day) && hour.Value.Check(nextUpdate.Hour) && minute.Value.Check(nextUpdate.Minute) && second.Value.Check(nextUpdate.Second))
                    return NodeResult.Success;

                nextUpdate = nextUpdate.AddSeconds(1);
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            double microseconds = (long)reader.Value / 1000.0;

            DateTime dateTime = new DateTime(1970, 1, 1);
            return dateTime.AddMilliseconds(microseconds);
        }
예제 #26
0
        /// <summary>
        /// 时间戳转DateTime
        /// </summary>
        /// <param name="mStamp"></param>
        /// <returns></returns>
        public static DateTime StampToDateTime(this long mStamp)
        {
            System.DateTime Time     = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            DateTime        dateTime = Time.AddMilliseconds(mStamp);

            return(dateTime);
        }
예제 #27
0
		public IAdaptingType read( FlashorbBinaryReader reader, ParseContext parseContext )
		{
			int refId = reader.ReadVarInteger();

			if( (refId & 0x1) == 0 )
				return (DateType) parseContext.getReference( refId >> 1 );

			double dateTime = reader.ReadDouble();

            DateTime sent = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc );

            try
            {
                sent = sent.AddMilliseconds(dateTime).ToLocalTime();
            }
            catch(Exception e)
            {
                if (Log.isLogging(LoggingConstants.EXCEPTION))
                    Log.log(LoggingConstants.EXCEPTION, e);

                sent = DateTime.MinValue;
            }

			DateType dateType = new DateType( sent );
			parseContext.addReference( dateType );
			return dateType;
		}
예제 #28
0
파일: Wheel.cs 프로젝트: Cylindric/Bot
 /// <summary>
 /// Set the desired speed of the wheel, and the time to take to get there (ease-in).
 /// If time is zero, the specified speed will be set on the next update.
 /// If time is non-zero, the speed will be reached in the specified time with a simple linear accelleration.
 /// </summary>
 /// <remarks>No changes are actually applied to the wheel until <see cref="update"/> is called.</remarks>
 /// <param name="speed">Target speed</param>
 /// <param name="time">Time to reach speed (millis)</param>
 public void SetSpeed(int speed, ulong time = 0)
 {
     SpeedRequestedAt = DateTime.Now;
     SpeedRequestedFor = SpeedRequestedAt.AddMilliseconds(time);
     RequestedStartSpeed = CurrentSpeed;
     RequestedTargetSpeed = Tools.Constrain(speed, -100, 100);
 }
예제 #29
0
 /// <summary>
 /// UNIX timestamp to System.DateTime
 /// </summary>
 /// <param name="unixTimeStamp"></param>
 /// <returns></returns>
 public DateTime UnixTimeStampToDateTime(double unixTimeStamp)
 {
     // First make a System.DateTime equivalent to the UNIX Epoch.
     var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
     // Add the number of seconds in UNIX timestamp to be converted.
     return dateTime.AddMilliseconds(unixTimeStamp);
 }
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      if (value == null)
        return "";

      double milliSecs = 0;
      if (!double.TryParse(value.ToString(), System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out milliSecs))
        return "";

      //unix epoch, UTC (also known as GMT)
      System.DateTime date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

      //add the specified milliseconds
      date = date.AddMilliseconds(milliSecs);

      //time stamp is UTC (also known as GMT) -> convert to local time zone
      date = TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);

      //return a culture-specific formatted date

      // Get the format string for the current UI culture
      string dateFormatString = CultureInfo.CurrentUICulture.DateTimeFormat.FullDateTimePattern;

      // Remove day and seconds from format string
      dateFormatString = Util.RemoveDayFormat(dateFormatString);
      dateFormatString = dateFormatString.Replace(":ss", "");

      // Replace two digit day with single digit
      dateFormatString = dateFormatString.Replace("dd", "d");

       // Trim leading and trailing whitespace
      dateFormatString = dateFormatString.Trim();

        return date.ToString(dateFormatString, CultureInfo.CurrentUICulture);
    }
예제 #31
0
 /// <summary>
 /// 将Unix时间戳转换为DateTime类型时间
 /// </summary>
 /// <param name="d">double 型数字</param>
 /// <returns>DateTime</returns>
 public static System.DateTime ConvertIntDateTime(double d)
 {
     System.DateTime time      = System.DateTime.MinValue;
     System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
     time = startTime.AddMilliseconds(d);
     return(time);
 }
예제 #32
0
 public ActionResult Audit(int ApplyID, string opt, DateTime SpreadBeginTime)
 {
     ViewBag.AmIn = "task";
     TaskBLL bll = new TaskBLL();
     Task task = bll.Get(ApplyID);
     task.AuditTime = DateTime.Now;
     if(opt == "pass")
     {
         DateTime dt = DateTime.Now;
         SpreadBeginTime.AddHours(dt.Hour);
         SpreadBeginTime.AddMinutes(dt.Minute);
         SpreadBeginTime.AddSeconds(dt.Second);
         SpreadBeginTime.AddMilliseconds(dt.Millisecond);
         task.SpreadBeginTime = SpreadBeginTime;
         task.Status = 1;
     }
     else if (opt == "deny")
     {
         task.Status = 2;
     }
     else
     { 
         //参数不正确
     }
     if(bll.Audit(task))
         return MyContent("审核任务成功,该任务被"+(opt == "deny" ? "拒绝" : "通过")+"!", "/Task/TaskList");
     return MyContent("审核失败!", "/Task/TaskList");
 }
예제 #33
0
        public void LogoutTimedOut()
        {
            bool sentLogout    = true;
            int  logoutTimeout = 2 * 1000;

            System.DateTime now          = System.DateTime.UtcNow;
            System.DateTime lastSentTime = now;

            now = now.AddMilliseconds(1000);
            Assert.False(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime));
            now = now.AddMilliseconds(1000);
            Assert.True(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime));

            sentLogout = false;
            Assert.False(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime));
        }
예제 #34
0
        /// <summary>
        /// 时间戳转换为datetime
        /// </summary>
        /// <param name="timeStamp">将毫秒字符串转换为时间格式</param>
        /// <returns></returns>
        public static DateTime GetDateTimeWithMilliSecond(long timeStamp)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(timeStamp);

            return(dt);
        }
예제 #35
0
 public static DateTime JavaTimeStampToDateTime(double javaTimeStamp)
 {
     // Java timestamp is millisecods past epoch
     System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
     dtDateTime = dtDateTime.AddMilliseconds(Math.Round(javaTimeStamp)).ToLocalTime();
     return dtDateTime;
 }
예제 #36
0
 public override void QueryQuote5(JObject jomsg)
 {
     #region 全量
     TickData     t           = new TickData();
     JObject      jtick_depth = jomsg;
     string[]     s           = jtick_depth["ch"].ToString().Split(new char[] { '.' });
     SecurityInfo si          = DicSi[s[1]];
     t.SecInfo = si;
     System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
     t.Time   = startTime.AddMilliseconds(System.Convert.ToDouble(jtick_depth["ts"].ToString()));
     t.Name   = si.Name;
     t.Code   = si.Code;
     t.IsReal = true;
     t.Bid    = System.Convert.ToDouble(jtick_depth["tick"]["bids"][0][0].ToString());
     t.Ask    = System.Convert.ToDouble(jtick_depth["tick"]["asks"][0][0].ToString());
     double last = CurrentTicker.getCurrentTickerPrice(market + s[1]);
     t.Last = last == 0 ? (t.Bid + t.Ask) / 2 : last;
     for (int i = 0; i < 10; i++)
     {
         t.Bids[i]     = System.Convert.ToDouble(jtick_depth["tick"]["bids"][i][0].ToString());
         t.Bidsizes[i] = System.Convert.ToDouble(jtick_depth["tick"]["bids"][i][1].ToString());
         t.Asks[i]     = System.Convert.ToDouble(jtick_depth["tick"]["asks"][i][0].ToString());
         t.Asksizes[i] = System.Convert.ToDouble(jtick_depth["tick"]["asks"][i][1].ToString());
     }
     RaiseQueryData(t);
     if (si.Code == this._querySi.Code && si.Market == market)
     {
         RaiseTradeQueryData(t);
     }
     #endregion
 }
예제 #37
0
        public static DateTime GetDateTimeFromTimeStamp(long stamp)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(stamp);

            return(dt);
        }
        public async Task<IEnumerable<UgEvent>> GetEvents(int count = 25) {
            var meetups = new List<UgEvent>();
            var meetupUrl = string.Format(_conf.Url, _conf.ApiKey, count);
            // TODO check cache here...extension method?
            var meetupJson = await _transport.GetAsync(meetupUrl);
            var meetupObject = JsonConvert.DeserializeObject<JObject>(meetupJson);

            // TODO decide where to put in the code to store stuff in the 
            // cache...

            Func<JToken, string> getValue = (j) => {
                return j == null ? null : j.ToString();
            };

            foreach (var mObj in meetupObject["results"]) {
                var m = new UgEvent();
                meetups.Add(m);

                m.Description = getValue(mObj["description"]);
                m.Name = getValue(mObj["name"]);
                m.EventUrl = getValue(mObj["event_url"]);
                var group = mObj["group"];
                if (group != null) {
                    m.GroupName = getValue(group["name"]);
                    m.GroupUrl = String.Format("http://meetup.com/{0}", getValue(group["urlname"]));
                    m.EventSource = "meetup.com";
                }

                DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
                m.EventDateTime = epoch.AddMilliseconds((double)mObj["time"]);
            }
            return meetups;
        }
예제 #39
0
파일: CTimer.cs 프로젝트: mzaman07/kot-mono
 public void start(int ticks)
 {
     _ticks     = ticks;
     _startTime = DateTime.Now;
     _stopTime  = _startTime.AddMilliseconds(_ticks);
     _active    = true;
 }
예제 #40
0
        //毫秒时间戳转成时间
        public static System.DateTime StampToUTCTimes(this long stamp)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(stamp);

            return(dt.ToUniversalTime());
        }
예제 #41
0
 public static DateTime ConvertIntDatetime(double utc)
 {
     System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
     startTime = startTime.AddMilliseconds(utc);
     //startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 )
     return(startTime);
 }
예제 #42
0
 public AnalogPoint(DateTime timeBase,byte[] data, int offset)
 {
     uint timeDiff = BitConverter.ToUInt32(data,offset);
     digitValue = (byte)(timeDiff & 0x0f);
     this.time = timeBase.AddMilliseconds(timeDiff >> 4);
     analogValue = BitConverter.ToSingle(data, offset + 4);
 }
 /// <summary>  
 /// 将Json序列化的时间由/Date(....)转为字符串
 /// </summary>
 private string ConvertJsonDateToDateString(Match m)
 {
     string result = string.Empty;
     DateTime dt = new DateTime(1970, 1, 1);
     dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)).ToLocalTime();
     return dt.ToString(FormateStr);
 }
예제 #44
0
 public static String convertTimestampToTime(long timestamp)
 {
     DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
     epoch = epoch.AddMilliseconds(timestamp);
     epoch = TimeZoneInfo.ConvertTimeFromUtc(epoch, TimeZoneInfo.Local);
     return epoch.ToString("HH':'mm");
 }
예제 #45
0
        //毫秒时间戳转成标准时间格式
        public static string StampToTimesFormat(this long stamp)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(stamp);

            return(dt.ToString("yyyy-MM-dd HH:mm:ss"));
        }
예제 #46
0
 public static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
 {
     // Unix timestamp is seconds past epoch
     System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
     dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
     return dtDateTime;
 }
예제 #47
0
        public static DateTime ToDateTime(long ticks)
        {
            DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            DateTime dateTime = start.AddMilliseconds(ticks).ToLocalTime();

            return dateTime;
        }
예제 #48
0
 public static DateTime UnixToDateTime(double j)
 {
     DateTime dt;
     dt = new DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
     dt = dt.AddMilliseconds(j).ToLocalTime();
     return dt;
 }
예제 #49
0
 public static DateTime Add(DatePartType datePart, long add, DateTime dt)
 {
     switch (datePart) {
     case DatePartType.Year:
         return dt.AddYears ((int)add);
     case DatePartType.Quarter:
         return dt.AddMonths ((int)add * 3);
     case DatePartType.Month:
         return dt.AddMonths ((int)add);
     case DatePartType.Day:
     case DatePartType.DayOfYear:
     case DatePartType.DayOfWeek:
         return dt.AddDays (add);
     case DatePartType.Hour:
         return dt.AddHours (add);
     case DatePartType.Minute:
         return dt.AddMinutes (add);
     case DatePartType.Second:
         return dt.AddSeconds (add);
     case DatePartType.MilliSecond:
         return dt.AddMilliseconds (add);
     case DatePartType.MicroSecond:
         return dt.AddTicks (add * TimeSpan.TicksPerMillisecond / 1000);
     case DatePartType.NanoSecond:
         return dt.AddTicks (add * TimeSpan.TicksPerMillisecond / 1000000);
     default:
         throw new InvalidOperationException (string.Format ("Unknown DatePart type '{0}'", datePart));
     }
 }
예제 #50
0
        public static DateTime IncrementDate(this TimePeriod period, DateTime date, int amount)
        {
            switch (period) {
                case TimePeriod.Millisecond:
                    return date.AddMilliseconds(amount);
                case TimePeriod.Second:
                    return date.AddSeconds(amount);
                case TimePeriod.Minute:
                    return date.AddMinutes(amount);
                case TimePeriod.Hour:
                    return date.AddHours(amount);
                case TimePeriod.Day:
                    return date.AddDays(amount);
                case TimePeriod.Month:
                    return date.AddMonths(amount);
                case TimePeriod.Quarter:
                    return date.AddMonths(amount * 3);
                case TimePeriod.Half:
                    return date.AddMonths(amount * 6);
                case TimePeriod.Year:
                    return date.AddYears(amount);

                default:
                    throw new Exception("Unknown period: " + period.ToString());

            }
        }
예제 #51
0
 public static DateTime convert2datetime(double utc)
 {
     // System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(2010, 1, 1));  // 舊版本
     System.DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(2010, 1, 1), TimeZoneInfo.Local);
     startTime = startTime.AddMilliseconds(utc);
     startTime = startTime.AddHours(8);
     return(startTime);
 }
예제 #52
0
 public void WaitNextTick()
 {
     nextTick = nextTick.AddMilliseconds(tickDuration);
     if (nextTick - System.DateTime.Now > TimeSpan.FromMilliseconds(0))
     {
         Thread.Sleep(nextTick - System.DateTime.Now);
     }
 }
예제 #53
0
        public void WithinHeartbeat()
        {
            int heartBtIntMillis = 60 * 1000;

            System.DateTime now              = System.DateTime.UtcNow;
            System.DateTime lastSentTime     = now;
            System.DateTime lastReceivedTime = now;

            now = now.AddMilliseconds(heartBtIntMillis - 1);
            Assert.True(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime));
            now = now.AddMilliseconds(1);
            Assert.False(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime));

            lastSentTime     = lastSentTime.AddMilliseconds(1);
            lastReceivedTime = lastReceivedTime.AddMilliseconds(1);
            Assert.True(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime));
        }
예제 #54
0
        public static DateTime GetDateTimeFromUnixInMillies(long millies)
        {
            // Format our new DateTime object to start at the UNIX Epoch
            System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

            // Add the timestamp (number of seconds since the Epoch) to be converted
            return(dateTime.AddMilliseconds(millies));
        }
예제 #55
0
파일: Time.cs 프로젝트: panning-he/planning
        /// <summary>
        /// 将Unix时间戳转换为DateTime类型时间
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static DateTime ConvrtToDateTimeFormMilliseconds(double d)
        {
            DateTime time      = System.DateTime.MinValue;
            DateTime startTime = new System.DateTime(1970, 1, 1);

            time = startTime.AddMilliseconds(d);
            return(time);
        }
예제 #56
0
        private static string UnixTimeStampToDateTime(long unixTimeStamp)
        {
            System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
            String time = dtDateTime.ToString("MM/dd/yyyy hh:mm:ss:ffff");

            return(time);
        }
예제 #57
0
        public void NeedTestRequest()
        {
            int heartBtIntMillis   = 30 * 1000;
            int testRequestCounter = 0;

            System.DateTime now = System.DateTime.UtcNow;
            System.DateTime lastReceivedTime = now;

            now = now.AddMilliseconds(heartBtIntMillis);
            Assert.False(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter));
            now = now.AddMilliseconds(heartBtIntMillis);
            Assert.True(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter));

            testRequestCounter += 1;
            Assert.False(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter));
            now = now.AddMilliseconds(heartBtIntMillis);
            Assert.True(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter));
        }
예제 #58
0
        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="jstimeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static DateTime GetTimeFromTimeStamp(long jstimeStamp)
        {
            //DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            //DateTime dt = startTime.AddSeconds(timeStamp);
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            DateTime        dt        = startTime.AddMilliseconds(jstimeStamp);

            return(dt);
        }
예제 #59
0
파일: Utils.cs 프로젝트: liuhanxu/LHJ
    /// <summary>
    /// 转换成当地时间
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static System.DateTime ToLocalTime(this object obj)
    {
        long time = (long)obj;

        //Debug.LogError(time);
        System.DateTime dt = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        dt = dt.AddMilliseconds((double)time).ToLocalTime();
        return(dt);
    }
예제 #60
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long jsTimeStamp = long.Parse(reader.Value.ToString());

            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            DateTime        dt        = startTime.AddMilliseconds(jsTimeStamp);

            return(dt);
        }