0

I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM" Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM). How can I split the Date and Time from a single string. Kindly Help. My approach right now is like :

string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();

But its throwing exception that string is not in correct format. Kindly help

Mahatma Aladdin
  • 2,027
  • 3
  • 17
  • 31

4 Answers4

4

@Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:

CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
3
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...

You are missing 4th 'y' in date format string:

"yyyy-MM-dd"
    ^
   here

and: String was not recognized as a valid DateTime " format dd/MM/yyyy"

Community
  • 1
  • 1
3

You need to specify the full format as same as the input string to parse method.

DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));

To get results you can use below methods available by default in DateTime.

dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"

Or you can specify the format to ToString method.

dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
Balaji Marimuthu
  • 1,940
  • 13
  • 13
2

Why do you parse into DateTime and then convert to a string using ToString again? Couldn´t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?

var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');

var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111