Beispiel #1
2
 /// <summary>
 ///     Returns a percentage of time elapsed from the assigned date to the due date
 /// </summary>
 /// <param name="assignedOn">Date assigned</param>
 /// <param name="dueOn">Date due</param>
 /// <returns>Normalized percent</returns>
 public static double GetPercentTime(DateTime assignedOn, DateTime dueOn)
 {
     TimeSpan totalTime = dueOn.Subtract(assignedOn);
     TimeSpan timeLeft = dueOn.Subtract(DateTime.Now);
     TimeSpan timeElapsed = totalTime.Subtract(timeLeft);
     return ((double) timeElapsed.Ticks / totalTime.Ticks);
 }
    static void Main()
    {
        DateTime start = new DateTime(2012, 1, 14);
        DateTime end = new DateTime(2013, 1, 25);

        if(start>end)
        {
            DateTime temp;
            temp = start;
            start = end;
            end = temp;
        }
        DateTime[] myDays = new DateTime[(int)end.Subtract(start).TotalDays];

        int daysToSubstract = 0;
        for (DateTime i = start; i <=end; )
        {
            for (int j = 0; j < holidays.Length; j++)
            {
                if(i==holidays[j])
                {
                    daysToSubstract++;
                }
            }
            if (i.DayOfWeek.ToString() == "Saturday" || i.DayOfWeek.ToString() == "Sunday")
            {
                daysToSubstract++;
            }
            i=i.AddDays(1);
        }

        Console.WriteLine("There are {0} days between {1:dd.MMMM.yyyy} and {2:dd.MMMM.yyyy}", end.Subtract(start).TotalDays,start,end);
        Console.WriteLine("{0} of these days are either a holiday or a weekend day",daysToSubstract);
        Console.WriteLine("So the total amount of work days is: {0}", end.Subtract(start).TotalDays-daysToSubstract);
    }
 internal OutputDebugStringEventArgs(int processId, DateTime messageTime, string messageText) {
     ProcessId = processId;
     MessageTime = messageTime;
     Message = messageText;
     SinceFirstEvent = messageTime.Subtract(Process.FirstMessageTime);
     SinceProcessStarted = messageTime.Subtract(Process.StartTime);
 }
        private int GetClosestIndexByDate(MarketSeries series, DateTime time)
        {
            var lastIndex = series.Close.Count - 1;

            if (time >= series.OpenTime[lastIndex])
                return lastIndex;

            var timeDifference = time.Subtract(series.OpenTime[0]);

            int index = 0;

            for (int i = 0; i < lastIndex - 1; i++)
            {
                if (time < series.OpenTime[i])
                    break;
                var currDiff = time.Subtract(series.OpenTime[i]);

                if (currDiff < timeDifference)
                {
                    timeDifference = currDiff;
                    index = i;
                }

            }

            return index;
        }
 public ActionResult KeyPerformanceIndicators(DateTime date)
 {
     dynamic data = new ExpandoObject();
     var orderVolume = salesDataWarehouseService.OrderVolume(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.RecentOrders = new ExpandoObject();
     data.RecentOrders.CurrentValue = orderVolume.Values.LastOrDefault();
     data.RecentOrders.HistoricalValues = orderVolume.Values.ToArray();
     var averageOrderValue = salesDataWarehouseService.AverageOrderValue(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.AverageOrderValue = new ExpandoObject();
     data.AverageOrderValue.CurrentValue = averageOrderValue.Values.LastOrDefault();
     data.AverageOrderValue.HistoricalValues = averageOrderValue.Values.ToArray();
     var uniqueCustomers = salesDataWarehouseService.UniqueCustomers(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.NewCustomerRatio = new ExpandoObject();
     data.NewCustomerRatio.CurrentValue = uniqueCustomers.Values.LastOrDefault().Item2;
     data.NewCustomerRatio.HistoricalValues = uniqueCustomers.Values.ToList().ConvertAll(item => item.Item1).ToArray();
     data.NewCustomerRatio.HistoricalUniqueCustomerValues = uniqueCustomers.Values.ToList().ConvertAll(item => item.Item2).ToArray();
     var uniqueSiteVisitors = salesDataWarehouseService.UniqueSiteVisitors(date, date.Subtract(TimeSpan.FromDays(SalesHistoryDayRange)));
     data.UniqueSiteVisitors = new ExpandoObject();
     data.UniqueSiteVisitors.CurrentValue = uniqueSiteVisitors.Values.LastOrDefault();
     data.UniqueSiteVisitors.HistoricalValues = uniqueSiteVisitors.Values.ToArray();
     return new JsonNetResult()
     {
         Data = data,
         HttpStatusCode = (int)System.Net.HttpStatusCode.OK,
         JsonRequestBehavior = JsonRequestBehavior.AllowGet
     };
 }
    public ThinkGearData DataAt(double secondsFromBeginning)
    {
        currentTime = DateTime.Now;

        deltaSeconds = currentTime.Subtract(startTime).TotalSeconds;

        elapsedSeconds += currentTime.Subtract(lastFrameTime).TotalSeconds;

        if(elapsedSeconds > BLINK_PERIOD){
          blinkValue = (int)(256.0f * (float)r.NextDouble());
          elapsedSeconds -= BLINK_PERIOD;
        }

        lastFrameTime = currentTime;

        return new ThinkGearData(secondsFromBeginning,
                             (int)(Math.Sin(deltaSeconds / 3.0f) * 50.0f + 50.0f),
                             (int)(Math.Cos(deltaSeconds / 3.0f) * 50.0f + 50.0f),
                             (int)(Math.Sin(deltaSeconds / 7.0f) * 50.0f + 50.0f),
                             0,
                             RandomValue(), RandomValue(),
                             RandomValue(), RandomValue(),
                             RandomValue(), RandomValue(),
                             RandomValue(), RandomValue(),
                             512.0f * (float)r.NextDouble(),
                             blinkValue);
    }
Beispiel #7
0
        private float scheduleTax(DateTime date)
        {
            System.DateTime yearTaxTo  = new System.DateTime(2016, 12, 31);
            System.DateTime monthTaxTo = new System.DateTime(2016, 5, 31);

            //daily tax scheduled = 0.1 (at days 2016.01.01 and 2016.12.25).
            if (DateTime.Equals(DateTime.Parse("2016-01-01"), date) || DateTime.Equals(DateTime.Parse("2016-12-25"), date))
            {
                return((float)0.1);
            }
            //monthly tax = 0.4 (for period 2016.05.01-2016.05.31),
            else if (monthTaxTo.Subtract(date).Days < 31 && monthTaxTo.Subtract(date).Days > 0)
            {
                return((float)0.4);
            }//yearly tax = 0.2 (for period 2016.01.01-2016.12.31)
            else if (yearTaxTo.Subtract(date).Days < 365 && yearTaxTo.Subtract(date).Days > 0)
            {
                System.TimeSpan d = date.Subtract(date);
                return((float)0.2);
            }
            else
            {
                Console.WriteLine("Date is outside the scheduled taxes");
                return(0);
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            var d = new DateTime(1970, 1, 1);

            var unspecified = new DateTime(d.Ticks, DateTimeKind.Unspecified);
            var local = new DateTime(d.Ticks, DateTimeKind.Local);
            var localInUtc = DateTime.SpecifyKind(local, DateTimeKind.Utc);

            var utc = new DateTime(d.Ticks, DateTimeKind.Utc);

            Debug.WriteLine("un as local: " + unspecified.ToLocalTime().ToLongTimeString());
            Debug.WriteLine("lo as local: " + local.ToLocalTime().ToLongTimeString());
            Debug.WriteLine("ut as local: " + utc.ToLocalTime().ToLongTimeString());

            Debug.WriteLine("un as utc: " + unspecified.ToUniversalTime().ToLongTimeString());
            Debug.WriteLine("lo as utc: " + local.ToUniversalTime().ToLongTimeString());
            Debug.WriteLine("ut as utc: " + utc.ToUniversalTime().ToLongTimeString());

            TimeSpan ts = unspecified.Subtract(local);
            ts = unspecified.Subtract(utc);
            ts = local.Subtract(utc);

            local = DateTime.SpecifyKind(d, DateTimeKind.Local);
            utc = DateTime.SpecifyKind(d, DateTimeKind.Utc);

            var unspecifiedTicks = unspecified.Ticks;
            var localTicks = local.Ticks;
            var utcTicks = utc.Ticks;
        }
        public void PrepareInputSeries_ThreeSeries_LastOne_StartsLater()
        {
            TripletAnalyser tripletAnalyser = new TripletAnalyser();
            IList<string> symbolList = new List<string>();
            DateTime minDate = new DateTime(2000, 1, 1);
            DateTime maxDate = new DateTime(2001, 1, 1);
            string exchange = "Exchange";
            string symbol = "Symbol_1";

            IStoreOHLCVIntervals intervalRepository = MockRepository.GenerateStub<IStoreOHLCVIntervals>();

            intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
                .Return(GenerateInputSeriesList(symbol, minDate, maxDate.Subtract(minDate).Days));

            symbol = "Symbol_2";
            intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
                 .Return(GenerateInputSeriesList(symbol, minDate, maxDate.Subtract(minDate).Days));

            symbol = "Symbol_3";
            intervalRepository.Stub(r => r.GetByTimeSpan(exchange, symbol, minDate, maxDate))
                 .Return(GenerateInputSeriesList(symbol, minDate.AddDays(10), maxDate.Subtract(minDate).Days));

            List<double[]> intersection = tripletAnalyser.PrepareInputSeries(new List<string>() { "Exchange:Symbol_1", "Exchange:Symbol_2", "Exchange:Symbol_3" }, minDate, maxDate, intervalRepository);

            Assert.AreEqual(3, intersection.Count);
            Assert.AreEqual(356, intersection[0].Length);
            Assert.AreEqual(356, intersection[1].Length);
            Assert.AreEqual(356, intersection[2].Length);
            Assert.LessOrEqual(Double.Epsilon, Math.Abs(minDate.AddDays(10).Ticks - intersection[0][0]));
            Assert.LessOrEqual(Double.Epsilon, Math.Abs(maxDate.Ticks - intersection[0][355]));
        }
Beispiel #10
0
        IEnumerator ProgressBarTime()
        {
            yield return(new WaitForSeconds(0.5f));

            startDate  = System.DateTime.Now;
            finishDate = startDate.AddSeconds(seconds);
            System.DateTime currentTime;
            TimeSpan        difference = finishDate.Subtract(startDate);

            while ((currentTime = System.DateTime.Now) <= finishDate)
            {
                TimeSpan currentDiference = finishDate.Subtract(currentTime);
                float    auxDiff          = (float)((currentDiference.TotalMilliseconds) / difference.TotalMilliseconds);
                float    percent          = 1.0f - auxDiff;
                ProgressBarObject.size = percent;

                LabelTime.text = currentDiference.Seconds + " seconds";

                yield return(new WaitForSeconds(0.05f));
            }
            ProgressBarObject.size = 1.0f;

            LabelTime.text = "";
            if (OnFinish != null)
            {
                OnFinish();
            }
        }
Beispiel #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.DateTime start = System.DateTime.Now;
        // Thread.Sleep(5000);

        Trace.Write("Deneme--1");
        Trace.Warn("Deneme--2");

        if (!Page.IsPostBack)
        {
            Trace.Write("In the postback method, before the GetFeaturedProducts request");
            DataView dw = new DataView(((DataLayer)Application["DataLayer"]).GetFeaturedProducts());
            dlFeatured.DataSource = dw;
            Trace.Write("Before databinding");
            dlFeatured.DataBind();
            Trace.Write("After databinding");
        }

        System.DateTime end = System.DateTime.Now;
        lblStartTime.Text = start.ToLongTimeString();
        string time = end.Subtract(start).Seconds + "." + end.Subtract(start).Milliseconds;

        lblExecutionTime.Text = end.Subtract(start).Seconds + "." + end.Subtract(start).Milliseconds;
        Trace.Warn("It took " + time + " to execute page_load");
    }
Beispiel #12
0
 public static ulong ToUnsignedDbTicks(DateTime d)
 {
     long dt = d.Subtract(JS_EPOCH).Ticks;
       if (dt < 0)
       {
     throw new Exception("Unsigned dbticks is negative");
       }
       return (ulong)(0.0001 * d.Subtract(JS_EPOCH).Ticks);
 }
        public IActionResult Index(string button)
        {
            System.DateTime start = System.DateTime.Now;

            DataLayer layer = new DataLayer();

            layer.GetFeaturedProducts();
            System.DateTime end = System.DateTime.Now;

            return(View("Index", end.Subtract(start).Seconds + "." + end.Subtract(start).Milliseconds));
        }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //MassTagDOATest massTagTest = new MassTagDOATest();
            SetupDataProviders(@"m:\data\proteomics\matest-gui\guitest.db3");
            MSFeatureDAOHibernate dao = new MSFeatureDAOHibernate();

            System.DateTime       start    = DateTime.Now;
            List <MSFeatureLight> features = dao.FindByDatasetId(0);

            System.DateTime end = DateTime.Now;
            //msFeatureTest.LoadMSFeaturesFromCache(@"m:\data\proteomics\matest-gui\guitest.db3");
            TimeSpan span = end.Subtract(start);

            System.Console.WriteLine("{0} total ms", span.TotalMilliseconds);

            MSFeatureDOATest msFeatureTest = new MSFeatureDOATest();

            start = System.DateTime.Now;
            msFeatureTest.LoadMSFeaturesFromCache(@"m:\data\proteomics\matest-gui\guitest.db3");
            end  = System.DateTime.Now;
            span = end.Subtract(start);
            System.Console.WriteLine("{0} total ms", span.TotalMilliseconds);
            //UMCFeatureFinding finding = new UMCFeatureFinding();
            //finding.Test();


            //return;

            //try
            //{
            //    string data = "-2147483648";
            //    long abu = Int64.Parse(data);

            //    UMCReaderFailure failTest = new UMCReaderFailure();
            //    failTest.Test();
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
            // SetupDataProviders();
            //MassTagDOATest massTagTest = new MassTagDOATest();
            //MSFeatureDOATest msFeatureTest = new MSFeatureDOATest();

            //msFeatureTest.LoadMSFeaturesFromCache(@"m:\data\proteomics\matest-gui\guitest.db3");

            //massTagTest.SaveMassTags();
            //msFeatureTest.SaveMSFeatures();

            //NHibernateUtil.CloseSession();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            System.DateTime batdau  = DateTime.Parse(Request.Form[TextBox4.UniqueID]);
            System.DateTime ketthuc = DateTime.Parse(Request.Form[TextBox5.UniqueID]);
            System.DateTime hientai = DateTime.Now;
            TimeSpan        ketqua  = ketthuc.Subtract(batdau);
            string          loi     = "";

            try
            {
                if (batdau.Subtract(hientai).TotalDays < 0 ||
                    batdau.Subtract(hientai).TotalDays > 1 ||
                    batdau.Subtract(hientai).TotalHours < 0 ||
                    batdau.Subtract(hientai).TotalHours > 24 ||
                    batdau.Subtract(hientai).TotalMinutes < 30)
                {
                    loi = "Thời điểm bắt đầu phải sau hiện tại ít nhất 30 phút để chuẩn bị! nhiều nhất 24 giờ";
                    int.Parse("aaaa");
                }

                if (ketthuc.Subtract(batdau).TotalDays < 0 ||
                    ketthuc.Subtract(batdau).TotalDays > 1 ||
                    ketthuc.Subtract(batdau).TotalHours < 0 ||
                    ketthuc.Subtract(batdau).TotalHours > 24 ||
                    ketthuc.Subtract(batdau).TotalMinutes < 5
                    )
                {
                    loi = "Thời điểm kết thúc phải sau thời điểm bắt đầu ít nhất 5 phút, nhiều nhất 24 giờ";
                    int.Parse("aaaa");
                }

                loi = "Lỗi dữ liệu!";
                SqlConnection connDB = new SqlConnection(connect.getconnect());
                SqlCommand    cmd    = new SqlCommand("giam_gia_sua", connDB);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@id_giam_gia", SqlDbType.NVarChar).Value                 = id_giam_gia;
                cmd.Parameters.Add("@ma_giam_gia", SqlDbType.NVarChar).Value                 = TextBox2.Text;
                cmd.Parameters.Add("@ten_giam_gia", SqlDbType.NVarChar).Value                = TextBox1.Text;
                cmd.Parameters.Add("@ly_do_giam_gia", SqlDbType.NVarChar).Value              = TextBox3.Text;
                cmd.Parameters.Add("@thoi_diem_bat_dau_giam_gia", SqlDbType.NVarChar).Value  = batdau.ToString();
                cmd.Parameters.Add("@thoi_diem_ket_thuc_giam_gia", SqlDbType.NVarChar).Value = ketthuc.ToString();
                connDB.Open();
                cmd.ExecuteNonQuery();
                connDB.Close();
                Response.Write("<script language='javascript'> alert('Sửa thành công');  window.open('./danhSach.aspx','_self', 1);</script>");
            }
            catch (Exception qr)
            {
                Response.Write("<script language='javascript'> alert('" + loi + "'); history.go(-1)</script>");
            }
        }
Beispiel #16
0
        //  Update the information of the timer
        //  !!!!!!!!!!!!!!!!!!!!!!!! The timer duration is decided by the end time and current time !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        protected virtual void update()
        {
            System.Threading.Thread.Sleep(20);
            currentTime = System.DateTime.Now;

            if (expire == false)                         //  Not expired
            {
                if (currentTime.CompareTo(endTime) <= 0) //  not expire
                {
                    diffTimeSpan = endTime.Subtract(currentTime);
                    if (diffTimeSpan.TotalMilliseconds < 100)    // Turn to expired
                    {
                        expire = true;
                        alarm  = true;
                        onAlarm();
                    }
                    else
                    {
                        ;
                    }
                }
                else   // expire
                {
                    expire       = true;
                    diffTimeSpan = currentTime.Subtract(endTime);
                }
            }

            else // expired
            {
                diffTimeSpan = currentTime.Subtract(endTime);
                if (diffTimeSpan.TotalMilliseconds > 3000)    // Stop alarming
                {
                    if (this.alarm)
                    {
                        this.alarm = false;
                        onAfterAlarm();
                    }
                }
            }

            // Send the update event.
            if (this.pause == false)    //  There is a bug in the onUpdate thread...
            {
                this.onUpdated();
            }

            Console.WriteLine("{0} - {1} = {2}, Alarm: {3}",
                              endTime, currentTime, diffTimeSpan.ToString(),
                              (alarm ? "Yes" : "No"));
        }
        public static decimal TinhTienCuoc(System.DateTime thoiGianBD, System.DateTime thoiGianKT)
        {
            decimal  kq    = 0;
            DateTime date1 = new DateTime(thoiGianBD.Year, thoiGianBD.Month, thoiGianBD.Day, 7, 00, 00);
            DateTime date2 = new DateTime(thoiGianBD.Year, thoiGianBD.Month, thoiGianBD.Day, 23, 00, 00);
            int      tgBD  = Int32.Parse(thoiGianBD.ToString("HH"));
            int      tgKT  = Int32.Parse(thoiGianKT.ToString("HH"));

            if ((tgBD >= 7 & tgKT < 23))
            {
                kq = thoiGianKT.Subtract(thoiGianBD).Hours * 60 + thoiGianKT.Subtract(thoiGianBD).Minutes;
                kq = kq * 200;
            }
            else if ((tgBD < 7 & tgKT >= 23))
            {
                decimal kq0 = (date2.Subtract(date1).Hours * 60 + date2.Subtract(date1).Minutes) * 200;
                decimal kq1 = (date1.Subtract(thoiGianBD).Hours * 60 + date1.Subtract(thoiGianBD).Minutes) * 150;
                decimal kq2 = (thoiGianKT.Subtract(date2).Hours * 60 + thoiGianKT.Subtract(date2).Minutes) * 150;
                kq = kq0 + kq1 + kq2;
            }
            else if ((tgBD < 7 & tgKT < 23))
            {
                decimal kq1 = (date1.Subtract(thoiGianBD).Hours * 60 + date1.Subtract(thoiGianBD).Minutes) * 150;
                decimal kq2 = (thoiGianKT.Subtract(date1).Hours * 60 + thoiGianKT.Subtract(date1).Minutes) * 200;
                kq = kq1 + kq2;
            }
            else if ((tgBD >= 7 & tgKT >= 23))
            {
                decimal kq1 = (date2.Subtract(thoiGianBD).Hours * 60 + date2.Subtract(thoiGianBD).Minutes) * 200;
                decimal kq2 = (thoiGianKT.Subtract(date2).Hours * 60 + thoiGianKT.Subtract(date2).Minutes) * 150;
                kq = kq1 + kq2;
            }
            return(kq);
        }
        private static bool IsLatable(Airline airline, System.DateTime TakeOffTime)
        {
            bool CanLate;

            if (airline.InterKbn == "国内")
            {
                CanLate = TakeOffTime.Subtract(airline.StartTime).TotalMinutes <= Utility.DelayDemasticMaxMinute;
            }
            else
            {
                CanLate = TakeOffTime.Subtract(airline.StartTime).TotalMinutes <= Utility.DelayInternationalMaxMinute;
            }

            return(CanLate);
        }
 public static DateTime GetCurrentIntervalTime(DateTime lastTime, DateTime newTime, Interval interval)
 {
     if (newTime.Subtract(lastTime) < AppConst.AppTimeSpans[interval])
     {
         return lastTime;
     }
     else
     {
         while (newTime.Subtract(lastTime) >= AppConst.AppTimeSpans[interval])
         {
             lastTime = lastTime.Add(AppConst.AppTimeSpans[interval]);
         }
         return lastTime;
     }
 }
	public void Calculate(){
		//define time points:
		startTime = new System.DateTime(1,1,1,(int)minValue,0,0,0);
		endTime = new System.DateTime(1,1,1,(int)maxValue,0,0,0);
				
		//correct 24 hour loop around:
		if (endTime.Subtract(startTime).Hours == 23) {
			endTime = startTime.AddDays(1);
		}else{
			endTime = endTime.AddHours(1);
		}
		
		//calculate duration:
		duration = endTime.Subtract(startTime);	
	}
Beispiel #21
0
    public void KeyDown(System.Object Sender, System.Windows.Forms.KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
        case Keys.Q:
            Label1.BackColor = Color.Green;
            dteStart         = DateAndTime.Now();
            break;

        case Keys.W:
            Label2.BackColor = Color.Green;
            break;

        case Keys.E:
            Label3.BackColor = Color.Green;
            break;

        case Keys.R:
            Label4.BackColor = Color.Green;
            dteFinish        = DateAndTime.Now();
            span             = dteFinish.Subtract(dteStart);
            Label5.Text      = span.ToString();

            break;
        }
    }
Beispiel #22
0
 public bool AddActivityLog(int userID, DateTime date)
 {
     try
     {
         int discount = 0;
         UserActivityLog log = new UserActivityLog();
         if (log.GetLastActivityByUserID(userID))
         {
             // get between days only i.e.
             // last day 01/03/2015 - current date  04/03/2015
             // the between days not equal 3 it's only 2 ( 02/03/2015 - 03-03-2015 )
             // so diff = current date - last date - 1
             discount = date.Subtract(log.Date).Days - 1;
         }
         log.AddNew();
         log.ComboUserID = userID;
         log.Date = date;
         log.DaysToDiscount = discount;
         log.Save();
         // if save success
         return true;
     }
     catch (Exception ex)
     {
         //if save fail - duplicate entry
         return false;
     }
 }
Beispiel #23
0
 private void l(string p)
 {
     
     dtOld = dtNew;
     dtNew = DateTime.Now;
     Console.WriteLine(dtNew.Subtract(dtOld).TotalMilliseconds.ToString().PadLeft(10," ".ToCharArray()[0]) + "\t\t" + p);
 }
Beispiel #24
0
        public Boolean suspend(string loginid)
        {
            DateTime      d1   = DateTime.Now;
            int           id   = Convert.ToInt32(loginid);
            SqlConnection CONN = new SqlConnection("Data Source=DESKTOP-GGK19TE\\SQLEXPRESS;Initial Catalog=facebooklogin;Integrated Security=True");

            CONN.Open();
            SqlCommand CMD = CONN.CreateCommand();

            CMD.CommandText = "select sus_date from Suspend_user";

            SqlDataReader sdr = CMD.ExecuteReader();

            while (sdr.Read())
            {
                suspend_date = sdr["sus_date"].ToString();
            }
            sdr.Close();
            CMD.ExecuteNonQuery();
            //DateTime dt = Convert.ToDateTime(suspend_date);
            //string differene = (d1 - dt).TotalDays;
            System.DateTime firstDate  = new System.DateTime();
            System.DateTime secondDate = new System.DateTime(2000, 05, 31);

            System.TimeSpan diff  = secondDate.Subtract(firstDate);
            System.TimeSpan diff1 = secondDate - firstDate;

            String diff2 = (secondDate - firstDate).TotalDays.ToString();

            // MessageBox.Show(diff1.ToString());
            return(true);
        }
Beispiel #25
0
 public static string GetTimeSpan(System.DateTime dtStartDate, System.DateTime dtEndDate)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     System.TimeSpan           timeSpan      = dtEndDate.Subtract(dtStartDate);
     if (timeSpan.Days != 0)
     {
         stringBuilder.AppendFormat("{0}天", timeSpan.Days);
     }
     if (timeSpan.Hours != 0)
     {
         stringBuilder.AppendFormat("{0}小时", timeSpan.Hours);
     }
     if (timeSpan.Minutes != 0)
     {
         stringBuilder.AppendFormat("{0}分钟", timeSpan.Minutes);
     }
     if (timeSpan.Seconds != 0)
     {
         stringBuilder.AppendFormat("{0}秒", timeSpan.Seconds);
     }
     if (string.IsNullOrEmpty(stringBuilder.ToString()))
     {
         return("0秒");
     }
     return(stringBuilder.ToString());
 }
        static string GetDaysAgo(DateTime date)
        {
            // We are hard coding the start do for consitent output.
            // In reality you would probably use DateTime.Now
            DateTime todayDate = new DateTime(2012, 4, 10);

            double daysAgo = todayDate.Subtract(date.Date).Days;
            int weeksAgo = (int)(daysAgo / 7.0);
            int monthsAgo = (int)(daysAgo / 30.0);
            int yearsAgo = (int)(daysAgo / 365.0);

            string measure = (yearsAgo==0)?((monthsAgo==0)?((weeksAgo==0)?"day":"week"):"month"):"year";
            int ago = (yearsAgo==0)?((monthsAgo==0)?((weeksAgo==0)?(int)Math.Floor(daysAgo):weeksAgo):monthsAgo):yearsAgo;

            string readable_format = "";
            bool special_format = false;

            if (measure == "day")
            {
                if (ago <= 1)
                {
                    special_format = true;
                    if (ago < 1) readable_format = "today";
                    else readable_format = "yesterday";
                }
            }

            if(!special_format)
            {
                readable_format = ago+" "+((ago>1)?measure+"s":measure);
            }
            return readable_format;
        }
        /// <summary>
        /// Asserts that a <see cref="DateTime"/> occurs a specified amount of time before another <see cref="DateTime"/>.
        /// </summary>
        /// <param name="target">
        /// The <see cref="DateTime"/> to compare the subject with.
        /// </param>
        /// <param name="because">
        /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not 
        /// start with the word <i>because</i>, it is prepended to the message.
        /// </param>
        /// <param name="reasonArgs">
        /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
        /// </param>
        public AndConstraint<DateTimeAssertions> Before(DateTime target, string because = "",
            params object[] reasonArgs)
        {
            bool success = Execute.Assertion
                .ForCondition(subject.HasValue)
                .BecauseOf(because, reasonArgs)
                .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText +
                          " {1} before {2}{reason}, but found a <null> DateTime.",
                    subject, timeSpan, target);

            if (success)
            {
                var actual = target.Subtract(subject.Value);

                if (!predicate.IsMatchedBy(actual, timeSpan))
                {
                    Execute.Assertion
                        .BecauseOf(because, reasonArgs)
                        .FailWith(
                            "Expected date and/or time {0} to be " + predicate.DisplayText +
                            " {1} before {2}{reason}, but it differs {3}.",
                            subject, timeSpan, target, actual);
                }
            }

            return new AndConstraint<DateTimeAssertions>(parentAssertions);
        }
Beispiel #28
0
        /// <summary>
        ///  通过串口向下位机发送报文信息(串口已经打开)
        ///  </summary>
        /// <param name="BuffMessage">存储报文信息缓冲区</param>
        /// <param name="commport">传输报文端口</param>
        /// <returns>true  发送成功
        ///          false 发送失败  </returns>
        public static bool SendMessage(byte[] BuffMessage, CommPort commport)
        {
            //串口已打开

            //获得当前系统时间
            System.DateTime Start_Time = new System.DateTime();
            Start_Time = System.DateTime.Now;
            while (true)
            {
                System.DateTime Now_Time = new System.DateTime();
                Now_Time = System.DateTime.Now;
                //传输时间大于20秒则传输失败
                TimeSpan Space_Time = Now_Time.Subtract(Start_Time);
                if (Space_Time.Seconds > 20)
                {
                    return(false);
                }
                else
                {
                    try
                    {
                        commport.Write(BuffMessage);
                        return(true);
                    }
                    catch
                    {
                        return(false);
                    }
                }
            }
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            int i = 42;

            i++;

            Console.WriteLine(i);

            System.DateTime da;
            da = System.DateTime.Now;

            Console.WriteLine(da);

            Console.WriteLine(da.ToString("d"));

            System.DateTime d1 = System.DateTime.Now;
            System.DateTime d2 = new System.DateTime(2018, 12, 24);
            System.TimeSpan ts = d2.Subtract(d1);
            Console.WriteLine(ts.TotalDays.ToString());

            System.DateTime d3 = System.DateTime.Now.AddMonths(1);

            System.TimeSpan ts2 = new TimeSpan(15, 00, 00);
            ts2 = ts2.Add(new TimeSpan(0, 20, 10));
            Console.WriteLine(ts2);

            System.Console.ReadLine();
        }
    public string GetClass(string today_time, string hour)
    {
        string baseDate = "2008/12/18";

        int count = 0;

        System.DateTime time1 = Convert.ToDateTime(baseDate);
        // System.DateTime time2 = Convert.ToDateTime(txtEstimateStartDate.SelectedDate.Value.ToString("yyyy/MM/dd"));
        System.DateTime time2 = Convert.ToDateTime(DateTime.Now.AddDays(+0).ToString("yyyy/MM/dd"));



        TimeSpan ts       = time2.Subtract(time1);
        Int32    diffm    = Convert.ToInt32(ts.TotalDays);
        Int32    diffm2   = diffm % 4;
        string   class_AB = "";
        string   class_DN = "";
        string   combine  = "";

        if (diffm2.Equals(0))
        {
            class_AB = "A(1)";
        }
        else if (diffm2.Equals(1))
        {
            class_AB = "A(2)";
        }
        else if (diffm2.Equals(2))
        {
            class_AB = "B(1)";
        }
        else
        {
            class_AB = "B(2)";
        }

        if (Convert.ToInt32(hour) > 7 && Convert.ToInt32(hour) < 19)
        {
            class_DN = "D";
        }
        else
        {
            class_DN = "N";
        }



        combine = class_DN + class_AB;

        combine = combine.Substring(0, 2);

        combine = combine.Replace("D", "日");
        combine = combine.Replace("N", "夜");


        // Label1.Visible = true;

        //Label1.Text = combine;
        return(combine);
    }
Beispiel #31
0
 public void PerformStep()
 {
     this.progressBar1.PerformStep();
     if (Command.ConfigFile.DebugProgressBar)
     {
         System.DateTime now      = System.DateTime.Now;
         System.TimeSpan timeSpan = now.Subtract(ProgressForm.LastTime);
         ProgressForm.LastTime = now;
         double totalMilliseconds = timeSpan.TotalMilliseconds;
         if (totalMilliseconds > 20.0)
         {
             Log.WriteLine("[{0}] >>>>>!!!!!!Perform Step: {1}", new object[]
             {
                 totalMilliseconds,
                 this.progressBar1.Value
             });
             return;
         }
         Log.WriteLine("[{0}] >>>>>Perform Step: {1}", new object[]
         {
             totalMilliseconds,
             this.progressBar1.Value
         });
     }
 }
Beispiel #32
0
        /// <summary>
        /// 得到两日期天数差值
        /// </summary>
        /// <param name="sDate">开始日期</param>
        /// <param name="eDate">结束日期</param>
        /// <returns>两日期天数差值</returns>
        public static int GetDateDiff(this System.DateTime sDate, System.DateTime eDate)
        {
            string days = "0";

            days = Convert.ToString(eDate.Subtract(sDate).Days);
            return(int.Parse(days));
        }
Beispiel #33
0
        WWW getCachedWWW(string url, TileInfo ti)
        {
            string filePath = GetLocalFilePathForUrl(url, ti);
            WWW    www;
            bool   useCached = false;

            useCached = _tileEnableLocalCache && System.IO.File.Exists(filePath);
            if (useCached)
            {
                if (!_tilePreloadTiles || !filePath.Contains(PREFIX_MIN_ZOOM_LEVEL))
                {
                    //check how old
                    System.DateTime written    = File.GetLastWriteTimeUtc(filePath);
                    System.DateTime now        = System.DateTime.UtcNow;
                    double          totalHours = now.Subtract(written).TotalHours;
                    if (totalHours > 300)
                    {
                        File.Delete(filePath);
                        useCached = false;
                    }
                }
            }
            ti.loadedFromCache = useCached;
            if (useCached)
            {
                string pathforwww = "file:///" + filePath;
                www = new WWW(pathforwww);
            }
            else
            {
                www = new WWW(url);
            }
            return(www);
        }
Beispiel #34
0
        public static long DateDiffDay(System.DateTime date1, System.DateTime date2)
        {
            TimeSpan timeSpan = date2.Subtract(date1);
            long     daydiff  = checked ((long)Math.Round(Conversion.Fix(timeSpan.TotalDays)));

            return(daydiff);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            SqlConnection  con   = new SqlConnection(DBClass.connectionstring);
            string         query = "select * from ToDOTable where id='" + comboBox2.Text + "'";
            DataTable      dt    = new DataTable();
            SqlDataAdapter da    = new SqlDataAdapter(query, con);

            con.Open();
            da.Fill(dt);
            con.Close();

            if (dt.Rows.Count > 0)
            {
                string s1 = dt.Rows[0]["start1"].ToString();
                string s2 = dt.Rows[0]["end1"].ToString();

                System.DateTime firstDate  = DateTime.Now.Date;//Convert.ToDateTime(s1);
                System.DateTime secondDate = Convert.ToDateTime(s2);;

                System.TimeSpan diff  = secondDate.Subtract(firstDate);
                System.TimeSpan diff1 = secondDate - firstDate;

                String diff2 = (secondDate - firstDate).TotalDays.ToString();



                // MessageBox.Show(diff1.ToString());

                label5.Text = diff2 + " Days are Left";
            }
        }
        /// <summary>
        /// This implementation was found on http://stackoverflow.com/questions/1285191/get-week-of-date-from-linq-query
        /// </summary>
        /// <param name="fromDate"></param>
        /// <returns></returns>
        private int WeekNumber(System.DateTime fromDate)
        {
            // Get jan 1st of the year
            var startOfYear = fromDate.AddDays(-fromDate.Day + 1).AddMonths(-fromDate.Month + 1);
            // Get dec 31st of the year
            var endOfYear = startOfYear.AddYears(1).AddDays(-1);

            // ISO 8601 weeks start with Monday
            // The first week of a year includes the first Thursday
            // DayOfWeek returns 0 for sunday up to 6 for saterday
            int[] iso8601Correction = { 6, 7, 8, 9, 10, 4, 5 };
            int   nds = fromDate.Subtract(startOfYear).Days + iso8601Correction[(int)startOfYear.DayOfWeek];
            int   wk  = nds / 7;

            switch (wk)
            {
            case 0:
                // Return weeknumber of dec 31st of the previous year
                return(WeekNumber(startOfYear.AddDays(-1)));

            case 53:
                // If dec 31st falls before thursday it is week 01 of next year
                if (endOfYear.DayOfWeek < DayOfWeek.Thursday)
                {
                    return(1);
                }
                return(wk);

            default: return(wk);
            }
        }
        public static int marsToday = 0; //DateTimeExtension.toMarsDay(DateTime.Now, earthDayOne); // met ça dans main

        #endregion Fields

        #region Methods

        public static int toMarsDay(DateTime earthToday, DateTime earthDayOne)
        {
            TimeSpan diff = earthToday.Subtract(earthDayOne);
            double diffSeconds = diff.TotalSeconds;
            double marsDay = diffSeconds / (24 * 60 * 60 + 40 * 60);
            return (int)Math.Ceiling(marsDay);
        }
Beispiel #38
0
 public static int DaysBetweenDates(string d1, string d2)
 {
     System.DateTime firstDate  = Convert.ToDateTime(d1);
     System.DateTime secondDate = Convert.ToDateTime(d2);
     System.TimeSpan diff       = secondDate.Subtract(firstDate);
     return((int)diff.TotalDays);
 }
Beispiel #39
0
 String DeterminarTempoOnline(DateTime dta_visto_ultimo)
 {
     DateTime agora = DateTime.Now;
     TimeSpan diferenca_tempo = agora.Subtract(dta_visto_ultimo);
     if (diferenca_tempo.TotalMinutes < 1)
         return "Online";
     else if (diferenca_tempo.TotalMinutes < 60)
         return "Há " + ((int)diferenca_tempo.TotalMinutes).ToString() + " minutos";
     else if (dta_visto_ultimo.Subtract(agora.Date).TotalDays >= 0)
         return "Hoje às " + dta_visto_ultimo.ToString("HH:mm");
     else if (dta_visto_ultimo.Subtract(agora.Date).TotalDays > -1)
         return "Ontem às " + dta_visto_ultimo.ToString("HH:mm");
     else if (dta_visto_ultimo == DateTime.MinValue)
         return "Nunca";
     return dta_visto_ultimo.ToString("dd/MM/yyyy HH:mm");
 }
 public void changeAppointmentDate(int appID, DateTime newStartDate, DateTime newEndDate)
 {
     appointment app = getAppointment(appID);
     app.appDate = newStartDate;
     app.appDuration = (int)newEndDate.Subtract(newStartDate).TotalMinutes;
     saveChanges();
 }
Beispiel #41
0
 /// <summary>
 /// 时间段比较,返回已分钟为单位
 /// </summary>
 /// <param name="DateTime1"></param>
 /// <param name="DateTime2"></param>
 /// <returns></returns>
 public static string DateMinueDiff(DateTime DateTime1, DateTime DateTime2)
 {
     string dateDiff = "";
     TimeSpan ts = DateTime1.Subtract(DateTime2);
     dateDiff = ts.TotalMinutes.ToString();
     return dateDiff;
 }
Beispiel #42
0
        public static long ToInt64(DateTime dateTime)
        {
            if (dateTime.Kind != DateTimeKind.Utc)
            dateTime = dateTime.ToUniversalTime();

              return (long)dateTime.Subtract(Epoch).TotalSeconds;
        }
Beispiel #43
0
    public static string GetSurplusTimeString(System.DateTime endTime)
    {
        System.TimeSpan span = endTime.Subtract(GetPSTDateTime());

        string timeStr   = "";
        string strDay    = Localization.instance.Get("IDS_MESSAGE_GLOBAL_DAY");
        string strHour   = Localization.instance.Get("IDS_MESSAGE_GLOBAL_HOUR");
        string strMinute = Localization.instance.Get("IDS_MESSAGE_GLOBAL_MINUTE");

        if (span.Days > 0)
        {
            timeStr = span.Days.ToString() + strDay;
        }
        else if (span.Hours > 0)
        {
            timeStr = span.Hours.ToString() + strHour;
        }
        else if (span.Minutes > 0)
        {
            timeStr = span.Minutes.ToString() + strMinute;
        }
        else if (span.Seconds > 0)
        {
            timeStr = "<1" + strMinute;
        }

        return(timeStr);
    }
Beispiel #44
0
        static void Main(string[] args)
        {
            Console.Write("Enter First Date(DD-MM-YY): ");
            string firstDate = Console.ReadLine();
            string[] dataOne = firstDate.Split('.');
            
            Console.Write("Enter Second Date(DD-MM-YY): ");
            string secondDate = Console.ReadLine();
            string[] dataTwo = secondDate.Split('.');


            DateTime timeOne = new DateTime(int.Parse(dataOne[2]), int.Parse(dataOne[1]), int.Parse(dataOne[0]));

            DateTime timeTwo = new DateTime(int.Parse(dataTwo[2]), int.Parse(dataTwo[1]), int.Parse(dataTwo[0]));

            TimeSpan diff;

            if (timeOne > timeTwo)
            {
                diff = timeOne.Subtract(timeTwo);
            }
            else
            {
                diff = timeTwo.Subtract(timeOne);
            }

            Console.WriteLine("Distance: " + diff.Days);
        }
        public void ValidMessage_ProducesValidJson()
        {
            var name = "foo";
            var value = 1923;
            var instance = "i-349da92";
            var collectedAt = new DateTime(2012, 1, 2);
            var collectedAtEpochSeconds = (long) collectedAt.Subtract(CustomMetricsMessage.EpochTime).TotalSeconds;
            var dp = new DataPoint(name, value, collectedAt, instance);

            var now = DateTime.UtcNow;
            var msg = new CustomMetricsMessage(dp);

            var json = msg.ToJson();
            Assert.NotNull(json);

            var deserialized = (JObject)JsonConvert.DeserializeObject(json);
            Assert.Equal(CustomMetricsMessage.ProtocolVersion, deserialized["proto_version"].Value<int>());
            Assert.True(deserialized["timestamp"].Value<long>() >= CustomMetricsMessage.EpochTime.Subtract(now).TotalSeconds);

            var pointsArray = deserialized["data"].Value<JArray>();
            Assert.NotNull(pointsArray);
            Assert.Equal(1, pointsArray.Count);

            var data0 = (JObject)pointsArray[0];
            Assert.Equal(name, data0["name"].Value<string>());
            Assert.Equal(value, data0["value"].Value<int>());
            Assert.Equal(instance, data0["instance"].Value<string>());
            Assert.Equal(collectedAtEpochSeconds, data0["collected_at"].Value<long>());
        }
Beispiel #46
0
        //returns debt to be payed
        private double calculatAndDisplayParkingDebt(int freeHours)
        {
            //Get actual time
            System.DateTime actualTime = System.DateTime.Now;

            //Get entrance time
            System.DateTime entranceTime = getEntranceTime();

            //Calculate debt
            double hoursDifference = Math.Ceiling(actualTime.Subtract(entranceTime).TotalHours);
            double hoursToPay      = hoursDifference - freeHours;

            if (hoursToPay < 0)
            {
                hoursToPay = 0;
            }

            double debtToPay = hoursToPay * pricePerHour;

            string hourOrHours = "hour";

            if (hoursToPay != 1)
            {
                hourOrHours = "hours";
            }

            actualParkingDebtLabel.Text = "$" + debtToPay + " (" + hoursToPay + " " + hourOrHours + ")";

            return(debtToPay);
        }
Beispiel #47
0
        public DateDiff(DateTime startDate, DateTime endDate)
            : this()
        {
            if (endDate < startDate) {
                throw new ArgumentException("endDate cannot be lesser then startDate");
            }

            var span = endDate.Subtract(startDate);
            Seconds = span.Seconds;
            Minutes = span.Minutes;
            Hours = span.Hours;

            if (endDate.Hour < startDate.Hour) {
                Days--;
            }
            if(endDate.Day >= startDate.Day) {
                Days += endDate.Day - startDate.Day;
            } else {
                Months--;
                var daysInMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);
                Days += daysInMonth - startDate.Day + endDate.Day;
            }

            if(endDate.Month >= startDate.Month) {
                Months += endDate.Month - startDate.Month ;
            } else {
                Months += MONTHS_IN_YEAR - startDate.Month + endDate.Month;
                Years--;
            }

            if (endDate.Year >= startDate.Year) {
                Years += endDate.Year - startDate.Year;
            }
        }
 public static int GetWeekOfMonth(DateTime date)
 {
     DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);
     while (date.Date.AddDays(1).DayOfWeek != DayOfWeek.Sunday)//CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
         date = date.AddDays(1);
     return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
 }
 public static int WeekNumber(DateTime fromDate)
 {
     // Get jan 1st of the year
     DateTime startOfYear = fromDate.AddDays(-fromDate.Day + 1).AddMonths(-fromDate.Month + 1);
     // Get dec 31st of the year
     DateTime endOfYear = startOfYear.AddYears(1).AddDays(-1);
     // ISO 8601 weeks start with Monday 
     // The first week of a year includes the first Thursday 
     // DayOfWeek returns 0 for sunday up to 6 for saterday
     int[] iso8601Correction = { 6, 7, 8, 9, 10, 4, 5 };
     int nds = fromDate.Subtract(startOfYear).Days + iso8601Correction[(int)startOfYear.DayOfWeek];
     int wk = nds / 7;
     switch (wk)
     {
         case 0:
             // Return weeknumber of dec 31st of the previous year
             return WeekNumber(startOfYear.AddDays(-1));
         case 53:
             // If dec 31st falls before thursday it is week 01 of next year
             if (endOfYear.DayOfWeek < DayOfWeek.Thursday)
                 return 1;
             else
                 return wk;
         default: return wk;
     }
 }
Beispiel #50
0
		private void SetNextDueTime(DateTime nextTaskTime)
		{
			double millisecondsOfDelay = nextTaskTime.Subtract(DateTime.UtcNow).TotalMilliseconds;

			int nextTimerInterval;

			if (millisecondsOfDelay >= int.MaxValue)
			{
				nextTimerInterval = _MaximumTimerIntervalInMilliseconds;
			}
			else if (millisecondsOfDelay < int.MinValue)
			{
				nextTimerInterval = _ImmediateTimerInterval;
			}
			else
			{
				nextTimerInterval = (int)millisecondsOfDelay;
			}

			if (nextTimerInterval <= _ImmediateTimerInterval)
			{
				_InternalTimer.Change(_ImmediateTimerInterval, Timeout.Infinite);
			}
			else if (nextTimerInterval >= _MaximumTimerIntervalInMilliseconds)
			{
				_InternalTimer.Change(_MaximumTimerIntervalInMilliseconds, Timeout.Infinite);
			}
			else
			{
				_InternalTimer.Change(nextTimerInterval + 1, Timeout.Infinite);
			}
		}
        public static List<double[]> PreverMediasPonderadaAleatoria(string nomeAtivo, DateTime dataInicio, DateTime dataTermino)
        {
            int quantMedia = 5;
            double peso = 0.5, pesoAux = 1;
            double divisor = 0;

            int quantDiasPrevisao = (int)dataTermino.Subtract(dataInicio).TotalDays;
            List<double[]> previsao;
            List<DadosBE> cotacoes = DataBaseUtils.DataBaseUtils.RecuperarCotacoesAtivo(nomeAtivo);

            previsao = cotacoes.Where(r => r.DataGeracao >= dataInicio.AddDays(-quantMedia)).Take(quantDiasPrevisao + quantMedia).Select(r => new double[] { (double)r.PrecoAbertura, (double)r.PrecoAbertura }).ToList();

            for (double i = (1 + peso); i <= (1 + peso * quantMedia); i += peso)
            {
                divisor += i;
            }

            for (int i = 0; i < quantMedia; i++)
            {
                previsao[i][1] = previsao[new Random(i).Next(0, (quantDiasPrevisao + quantMedia) - 1)][0];
            }

            for (int i = quantMedia; i < quantDiasPrevisao + quantMedia; i++)
            {
                previsao[i][1] = previsao.Skip(i - quantMedia).Take(quantMedia).Select(cot => cot[1] * (pesoAux += peso)).Sum() / divisor;
                pesoAux = 1;
            }

            return previsao.Skip(quantMedia).ToList();
        }
Beispiel #52
0
 /// <summary>
 /// This method converts DateTime to a float, which represents the hours since data collection started.
 /// </summary>
 public float DateToHours(System.DateTime dateTime)
 {
     // subtract the very first DateTime from the the given DateTime
     System.TimeSpan timeSpan = dateTime.Subtract((System.DateTime)statistics.GetPoints()[0].GetX());
     // round to three decimal places and return it
     return(Mathf.Round((float)(timeSpan.TotalHours * 1000f)) / 1000f);
 }
Beispiel #53
0
        /// <summary> Converts a Date to a string suitable for indexing.</summary>
        /// <throws>  RuntimeException if the date specified in the </throws>
        /// <summary> method argument is before 1970
        /// </summary>
        public static System.String DateToString(System.DateTime date)
        {
            TimeSpan ts = date.Subtract(new DateTime(1970, 1, 1));

            ts = ts.Subtract(TimeZone.CurrentTimeZone.GetUtcOffset(date));
            return(TimeToString(ts.Ticks / TimeSpan.TicksPerMillisecond));
        }
Beispiel #54
0
        private void checkOverdue(string file)
        {
            string  line;
            Boolean update = false;

            StreamReader filePath      = new StreamReader(file);
            int          overdueDays   = 0;
            int          overdueMovies = 0;

            while ((line = filePath.ReadLine()) != null)
            {
                string[] customerInfo = line.Split(',');

                string barcode = customerInfo[1];
                if (checkReturn(barcode))
                {
                    update = true;
                    updateCustomerFile(barcode, file);
                    continue;
                }


                System.DateTime today = new System.DateTime();
                today = System.DateTime.Today;
                string day   = customerInfo[3];
                string month = customerInfo[2];
                string year  = customerInfo[4];

                int dateDay;
                int dateMonth;
                int dateYear;

                int.TryParse(day, out dateDay);
                int.TryParse(month, out dateMonth);
                int.TryParse(year, out dateYear);

                System.DateTime checkedOut = new System.DateTime(dateYear, dateMonth, dateDay);

                System.TimeSpan late = today.Subtract(checkedOut);

                int lateDays = late.Days;
                if (lateDays > 0)
                {
                    overdueDays += lateDays;
                    overdueMovies++;
                }
            }
            filePath.Close();

            if (update)
            {
                File.Delete(file);
                File.Move("..\\Files\\temp.txt", file);
                update = false;
            }
            if (overdueMovies > 0)
            {
                MessageBox.Show("Inform customer they have " + overdueMovies + " overdue movies for " + overdueDays + " days in late fees");
            }
        }
Beispiel #55
0
        public static int ToInt32(DateTime dateTime)
        {
            if (dateTime.Kind != DateTimeKind.Utc)
            dateTime = dateTime.ToUniversalTime();

              return (int)dateTime.Subtract(Epoch).TotalSeconds;
        }
Beispiel #56
0
    //===================================================================================================================

    private void updateDisplay(System.DateTime currentTime)
    {
        //Calculate the time left, get a string from that.
        System.TimeSpan timeLeft = endTime.Subtract(currentTime);
        string          text     = timeLeft.ToString();

        //Modify the string for pretty display.
        if (timeLeft.Days == 0)
        {
            text = text.Insert(0, "000:");
        }
        else
        {
            text = text.Replace(".", ":");
            if (timeLeft.Days < 10)
            {
                text = text.Insert(0, "0");
            }
            if (timeLeft.Days < 100)
            {
                text = text.Insert(0, "0");
            }
        }

        //Display the text.
        display.text = text;

        //Todo: play a sound.
        playTic(currentTime.Second % 2 == 0);
    }
        private BaseUnit GetBaseUnit(DateTime dateFrom, DateTime dateTo)
        {
            var diff = dateTo.Subtract(dateFrom);
            var days = diff.TotalDays;
            var result = BaseUnit.Years;

            // Try to maintain groups count below TARGET_RESULT_SIZE
            if (diff.TotalMinutes < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Minutes;
            }
            else if (diff.TotalHours < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Hours;
            }
            else if (days < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Days;
            }
            else if (days / DAYS_PER_WEEK < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Weeks;
            }
            else if (days / DAYS_PER_MONTH < TARGET_RESULT_SIZE)
            {
                result = BaseUnit.Months;
            }

            return result;
        }
        public void AddPoint(DateTime dt, int nb)
        {
            TimeSpan ts = dt.Subtract(dt_start);
            PointF new_p = new PointF((float)ts.TotalMinutes * x_mod / 60f, y_tab + height - (y_mod * (nb + 1f)));
            if (last_p == PointF.Empty)
                last_p = new_p;

            using (Graphics g = Graphics.FromImage(Graphique))
            {
                using (Pen p = new Pen(Color.Red, 4f))
                    g.DrawLine(p, last_p, new_p);
                using (SolidBrush sb = new SolidBrush(Color.Black))
                using (FontFamily ff = new FontFamily("Trebuchet MS"))
                using (Font f = new Font(ff, 8, FontStyle.Regular))
                    g.DrawString(nb + "", f, sb, new_p);
            }

            if (new_p.X > width)
            {
                Save();
                DrawGraphBackground();

                new_p.X = new_p.X - width;
                last_p.X = last_p.X - width;

                AddPoint(dt, nb);
            }
            else
                last_p = new_p;
        }
Beispiel #59
0
        ///   <summary>
        ///   返回两个日期之间的时间间隔(y:年份间隔、M:月份间隔、d:天数间隔、h:小时间隔、m:分钟间隔、s:秒钟间隔、ms:微秒间隔)
        ///   </summary>
        ///   <param   name="Date1">开始日期</param>
        ///   <param   name="Date2">结束日期</param>
        ///   <param   name="Interval">间隔标志</param>
        ///   <returns>返回间隔标志指定的时间间隔</returns>
        public static int DateDiff(System.DateTime Date1, System.DateTime Date2, string Interval)
        {
            double dblYearLen  = 365;        //年的长度,365天
            double dblMonthLen = (365 / 12); //每个月平均的天数

            System.TimeSpan objT;
            objT = Date2.Subtract(Date1);
            switch (Interval)
            {
            case "y":    //返回日期的年份间隔
                return(System.Convert.ToInt32(objT.Days / dblYearLen));

            case "M":    //返回日期的月份间隔
                return(System.Convert.ToInt32(objT.Days / dblMonthLen));

            case "d":    //返回日期的天数间隔
                return(objT.Days);

            case "h":    //返回日期的小时间隔
                return(objT.Hours);

            case "m":    //返回日期的分钟间隔
                return(objT.Minutes);

            case "s":    //返回日期的秒钟间隔
                return(objT.Seconds);

            case "ms":    //返回时间的微秒间隔
                return(objT.Milliseconds);

            default:
                break;
            }
            return(0);
        }
Beispiel #60
0
        // todo delete unused

        public static void DownloadOrChache(string url, Action <Sprite> onDownloaded)
        {
            string filePath = Application.persistentDataPath;

            filePath += "cache/" + url.GetHashCode();

            bool existsInChache = System.IO.File.Exists(filePath);

            string localPath = "file:///" + filePath;

            if (existsInChache)
            {
                // check if not too old
                System.DateTime written  = File.GetLastWriteTimeUtc(filePath);
                System.DateTime now      = System.DateTime.UtcNow;
                double          lifetime = now.Subtract(written).TotalSeconds;
                if (lifetime > SecondsToExpire)
                {
                    File.Delete(filePath);
                    DialogueManager.Instance.StartCoroutine(Download(url, filePath, onDownloaded));
                }
                else
                {
                    DialogueManager.Instance.StartCoroutine(Download(localPath, filePath, onDownloaded));
                }
            }
            else
            {
                DialogueManager.Instance.StartCoroutine(Download(url, filePath, onDownloaded));
            }
        }