Newbie
Newbie

Reputation: 1180

Windows Phone - C# - Formatting DateTime correctly

In my application I have a procedure which sets a reminder on the phone for any given time. However I have a problem with formatting the date and time correctly.

I have two strings one with the date in either dd/MM/yyyy or MM/dd/yyyy format, and another string with the date in 24hour format.

How can I format these two strings into DateTime? I've tried DateTime.Parse(date+time); but that doesn't work.

Here's the full set of code:

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);
        }

Thank you, your help is greatly appreciated!

Upvotes: 1

Views: 684

Answers (1)

SynerCoder
SynerCoder

Reputation: 12766

Use 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
};

Make sure the pattern matches your date & time pattern. To separate the date and time I added a space just like there is one in my pattern.

For full list of specifiers: MSDN

Upvotes: 1

Related Questions