在我的应用程序中,我有一个程序,可以在任何给定时间在手机上设置提醒。但是我在正确格式化日期和时间方面遇到了问题。
我有两个字符串,其中日期为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 :(得分:1)
使用DateTime.ParseExact
(MSDN)。
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