2012-02-14 138 views
0

如果我調用此方法的順序性,日期格式問題

object[] ab = GetSomething(myObject); 

我得到的日期時間格式是這樣,這是確定

enter image description here

知道如果我使用第三方物流,調用該方法

Task t1 = Task.Factory.StartNew(() => GetSomething(myObject)); 
Task t2 = Task.Factory.StartNew(() => GetSomeOtherthing(myObject)); 
Task.WaitAll(t1, t2); 

我與AM/PM這種格式是causi ng轉換失敗,說無效的日期時間格式,有沒有辦法像順序方法改變日期時間formart。

enter image description here

我是多麼轉換字符串日期時間

Search.Date = Convert.ToDateTime(myObject.ToDate, CultureInfo.InvariantCulture); 
+2

什麼是'被設置'Date' GetSomething'的代碼? – 2012-02-14 17:10:28

+0

@NeilKnight使用Convert.ToDateTime(myObject.ToDate)的iam採用字符串格式 – 2012-02-14 17:15:05

+0

接下來的問題是'myObject'上的'ToDate'是什麼?屬性?它是如何實現的?它的數據類型是什麼? – 2012-02-14 17:17:41

回答

1

從/轉換爲字符串時,應始終明確指定的文化。

在你的情況下,線程池線程可能與你所期望的不同CurrentCulture。

+0

有沒有辦法將線程池線程CurrentCulture更改爲特定的線程池線程。 – 2012-02-14 17:59:08

+3

@ AI25我會避免這種情況。 'DateTime.Parse'和類似的函數有一個參數,需要一種文化。使用那個。 – CodesInChaos 2012-02-14 18:02:11

+0

如果您使用不使用特定CultureInfo而使用DateTime.Pars/DateTime.ToString的庫,那麼該怎麼辦......我認爲您需要在Thread上設置CurrentCulture。 – Jaap 2012-04-26 09:51:04

1

如果您想更改線程的文化,然後創建自己的知道應用程序文化的任務計劃程序。調度程序可以在執行任務之前調整文化。

這是一個樣本調度...

class LocalizedTaskScheduler : TaskScheduler 
{ 
    public CultureInfo Culture { get; set; } 
    public CultureInfo UICulture { get; set; } 

    #region Overrides of TaskScheduler 

    protected override void QueueTask(Task task) 
    { 
     //Queue the task in the thread pool 
     ThreadPool.UnsafeQueueUserWorkItem(_ => 
     { 
      //Adjust the thread culture 
      Thread.CurrentThread.CurrentCulture = this.Culture; 
      Thread.CurrentThread.CurrentUICulture = this.UICulture; 
      //Execute the task 
      TryExecuteTask(task); 
     }, null); 
    } 

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) 
    { 
     if (taskWasPreviouslyQueued) 
     { 
      return false; 
     } 
     // Try to run the task. 
     return base.TryExecuteTask(task); 
    } 

    protected override IEnumerable<Task> GetScheduledTasks() 
    { 
     //We have no queue 
     return Enumerable.Empty<Task>(); 
    } 

    #endregion 
}