2013-07-10 44 views
1

在我的應用程序中,我有一個程序,可以在任何給定時間在手機上設置提醒。不過,我正確地格式化日期和時間有問題。Windows Phone - C# - 正確格式化DateTime

我有兩個字符串之一,日期爲dd/MM/yyyy或MM/dd/yyyy格式,另一個字符串的日期爲24小時格式。

如何將這兩個字符串格式化爲DateTime?我試過DateTime.Parse(date+time);但這不起作用。

下面是完整的一套代碼:

public void setReminder(string fileTitle, string fileContent, string fileDate, string fileTime) 
     { 
      string dateAndTime = fileDate + fileTime; 

      if (ScheduledActionService.Find(fileTitle) != null) 
       ScheduledActionService.Remove(fileTitle); 
      Reminder r = new Reminder(fileTitle) 
      { 
       Content = fileContent, 
       BeginTime = DateTime.Parse(fileDate+fileTime), 
       Title = fileTitle 
      }; 
      ScheduledActionService.Add(r); 
     } 

謝謝你的幫助是非常感謝!

+0

也許fileDate +「」+ fileTime?您將它們組合起來的方式看起來像01/01/200023:00:00。這裏需要一個空間。 – Jonesopolis

+0

這沒有奏效,後來導致錯誤。 – Newbie

+0

如果它可能是dd/MM或MM/dd,並且您不確定哪些是哪個,那麼您無法可靠地解析日期。哪個月是12/11?十一月或十二月?我希望它很重要,除非你知道它是哪種格式,否則你無法知道。 –

回答

1

使用DateTime.ParseExactMSDN)。

string dateAndTime = fileDate + " " + fileTime; 
string pattern = "dd/MM/yyyy HH:mm:ss"; 

Reminder r = new Reminder(fileTitle) 
{ 
    Content = fileContent, 
    BeginTime = DateTime.ParseExact(dateAndTime, pattern, CultureInfo.InvariantCulture), 
    Title = fileTitle 
}; 

確保你的模式日期&時間模式相匹配。爲了分離日期和時間,我添加了一個空格,就像我的模式中有一個空格。

有關說明符的完整列表:MSDN

+0

謝謝生病,我在一分鐘內試了一下,但是我該怎麼處理日期,因爲它可能是歐洲或美國的格式,所以我不會能夠在你建議的方法下指定格式? – Newbie

+0

你無法知道。如果我們採取日期:03/06/2013你能告訴我,如果是3月6日3日或3日?如果你不能告訴我,電腦怎麼知道? – SynerCoder

+0

啊,公平點。 – Newbie