简体   繁体   中英

convert string to datetime format and date only in c#

How can I convert the string to datetime. I have following string:

08/19/2012 04:33:37 PM

I want to convert above string to following format date:

MM-dd-yyyy

and

dd/MM/yyyy HH:mm:ss

I have been trying to convert using different technique and using following:

DateTime firstdate = DateTime.Parse(startdatestring);

It shows following error

String was not recognized as a valid DateTime.

I have search for it and couldn't get exact solution and also try using different format for datetime. Please how can I convert above string to above date format

You need to parse the string first - you have missed out the AM/PM designator. Take a look at Custom Date and Time Format Strings on MSDN:

DateTime firstdate = DateTime.ParseExact(startdatestring, 
                                         "MM/dd/yyyy hh:mm:ss tt",
                                         CultureInfo.InvariantCulture);

Then you can format to a string:

var firstDateString = firstdate.ToString("MM-dd-yyyy");

Which you may also want to do with InvariantCulture :

var firstDateString = firstdate.ToString("MM-dd-yyyy", 
                                         CultureInfo.InvariantCulture);

In .NET 6 you can use the DateOnly struct

var dateTime = DateTime.Parse("08/19/2012 04:33:37 PM");

var dateOnly = DateOnly.FromDateTime(dateTime);
var dateOnlyString = dateOnly.ToString("MM-dd-yyyy");

or

var dateOnlyString = DateOnly.Parse("08/19/2012").ToString("MM-dd-yyyy");

Output: 08-19-2012

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM