2017-02-17 46 views
0

我正在創建一個應用程序,告訴我剩下多少時間才能打開或關閉外匯市場。C#如何計算即將到來的特定時間?

Image

例如,如果紐約市場剛一靠近,現在我想知道多少時間是留給紐約市場再次打開。有些公司在關閉時打開它。

我可以使用計時器來減少剩餘時間,但問題是我無法獲得絕對減去的剩餘時間值。甚至沒有TimeSpan.Subtract或DateTime.Subtract。

編輯:我使用此代碼來告訴我,市場是開放的

if ((IsTimeOfDayBetween(DateTime.UtcNow, new TimeSpan(8, 0, 0), new TimeSpan(16, 0, 0))) == true) 
    { 
     textBox1.Background = new SolidColorBrush(Colors.Green); 

    } 

但關閉後,我想剩下的時間留給它再次打開,顯示文本塊中。

回答

0

你可以嘗試這樣的事情,使用功能「IsTimeOfDayBetween」你已經有:

// global variables 
    TimeSpan dayStart = new TimeSpan(0, 0, 0); 
    TimeSpan dayEnds = new TimeSpan(23, 59, 59); 

    // you have a timer(loop) every sencond, so you can have this two variables change depending on what market you are tracking, in this example NY 
    TimeSpan NyOpens = new TimeSpan(8, 0, 0); 
    TimeSpan NyClose = new TimeSpan(16, 0, 0); 

    // variable to store the result 
    TimeSpan tillOpenClose; 

    if ((IsTimeOfDayBetween(DateTime.UtcNow, NyOpens, NyClose)) == true) 
    { 
     textBox1.Background = new SolidColorBrush(Colors.Green); 
     // its open, you want time till close 
     // validate close time is greater than open time 
     if (NyClose.CompareTo(NyOpens) > 0) 
      tillOpenClose = NyClose.Subtract(DateTime.UtcNow.TimeOfDay); 
     else 
      tillOpenClose = ((dayEnds.Subtract(DateTime.UtcNow.AddSeconds(-1).TimeOfDay)).Add(NyClose)); // if the market closes at and earlier time, then the time till close, is the remaing time of this day, plus the time till close of the new day 
    } 
    else if ((IsTimeOfDayBetween(DateTime.UtcNow, dayStart, NyOpens)) == true) // if time is between start of day and open time 
     tillOpenClose = NyOpens.Subtract(DateTime.UtcNow.TimeOfDay); 
    else // it is between closetime and end of day 
     tillOpenClose = ((dayEnds.Subtract(DateTime.UtcNow.AddSeconds(-1).TimeOfDay)).Add(NyOpens)); // part remaining for this day plus new day, the extra second is to compensate the "dayEnds" 

    Console.WriteLine(tillOpenClose.ToString(@"hh\:mm\:ss")); 

與「IsTimeOfDayBetween」功能應該是這樣的這樣的:

if (open.CompareTo(close) > 0) // if open time is greater (e.g. open: (20,0,0) close: (4,0,0)) 
    { 
     if (timeNow.TimeOfDay.CompareTo(open) >= 0 || timeNow.TimeOfDay.CompareTo(close) <= 0) 
      return true; 
    } 
    else 
    { 
     if (timeNow.TimeOfDay.CompareTo(open) >= 0 && timeNow.TimeOfDay.CompareTo(close) <= 0) 
      return true; 
    } 

    return false; 

編輯:改變的時間,直到接近,比較遺憾的是

編輯2:調整關閉時間早於開放時間

+0

像魅力一樣工作。謝謝 ! – Suleman

+0

@Suleman,沒問題......對不起,我剛剛編輯了答案,以考慮在新的一天的關閉時間。希望它正是你所需要的 – karkazz

-1

請嘗試下面的代碼。我希望它`幫助您的問題

var dt = new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); 

    var now = System.DateTime.Now.ToUniversalTime(); 
    var future = new DateTime(2010, 1, 1).ToUniversalTime(); 

    Console.WriteLine((now - dt).TotalSeconds); 
    Console.WriteLine((future - dt).TotalSeconds); 
+0

這是如何回答的問題? – Enigmativity