Reputation: 15
I have a variable openDate
which holds date and time, and I would like to strip just the date. I tried the below example and it is not working. What am I doing wrong, or rather how should I do it because the variable openDate
remains the same even after trying to strip just the date? The value of openDate
is "2012-03-08 00:00:00"
openDate = ! string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)
? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value
: "" ;
openDate = String.Format("{0:MM/dd/yyyy}", openDate);
Upvotes: 0
Views: 435
Reputation: 4685
The answers are great, especially if you would like to control the format of your 'time' part. Here is teh simplest way to get what you are after:
var dt = Convert.ToDateTime("2012-03-08 00:00:04");
Console.WriteLine(dt.ToLongTimeString());
Console.WriteLine(dt.TimeOfDay);
Output:
Upvotes: 0
Reputation: 439
You can format datetime using: If it is a datetime:
OpenDate = OpenDate.ToString("yyyy-mm-dd");
If the datatype is not datetime and you are sure the format will always be that then you can always convcert the string to datetime and use the method described above.
Convert.ToDateTime(openDate).ToString("yyyy-mm-dd");
Upvotes: 0
Reputation: 223257
From your code it is clear that openDate
is of type string and you have value that is a string representation of DateTime
, you can apply DateTime
formatting on string values.
You have multiple options.
string
openDate
to a DateTime
value and then apply formattingString operations:
string openDate = "2012-03-08 00:00:00";
string formatted = openDate.Substring(0, openDate.IndexOf(' '));
DateTime
Parsing.
DateTime parsedDateTime = DateTime.Parse(openDate);
string formattedDateTime = parsedDateTime.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 616
considering openDate
is of a String type, i would do this
var dt = DateTime.Parse(openDate).ToString("MM/dd/yyyy");
Upvotes: 1
Reputation: 22911
You need to convert your date into a DateTime
object first. See examples here if your string is in a different or custom format.
openDate = !string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value: "" ;
//openDate is a string at this point. You'll need to convert it to a datetime object first, for the following line to work:
var dtObject = DateTime.Parse(openDate);
//Format the newly created datetime object
openDate = String.Format("{0:MM/dd/yyyy}", dtObject);
Upvotes: 0