简体   繁体   中英

How to parse string into specific format of date time in c#

I have a string in c# which contains date time value.Now as per my requirement i have to parse this string into Datetime as my mysql database table contains column name like this ..

`call_time` datetime NOT NULL,

Here is my string datetime Value

String datetime="11/02 05:01";

Now as per my requirement i have to parse this string into datetime datatype of mysql field.

Please help me.

在C#中

var date = DateTime.ParseExact(datetime, "dd/MM HH:mm", CultureInfo.InvariantCulture)

You can parse a string representation of a date into an actual DateTime like this:

var date = DateTime.ParseExact(datetime, "dd/MM HH:mm", CultureInfo.InvariantCulture)

It assumes the year is the current year since that's not provided, and treats the hour as 24-hour since you don't have AM/PM. You'll get something like this:

2/11/2014 5:01:00 AM

Try this:

String datetime="11/02 05:01";
DateTime dt =  DateTime.ParseExact(datetime, "dd/MM HH:mm", CultureInfo.InvariantCulture);

DateTime.ParseExact converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

Syntax:

public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider
)

Read more here .

Without defining date format it is too dificult to convert string into datetime. following example will take current year in result

CultureInfo culture = CultureInfo.InvariantCulture;
string dtFormat = "dd/MM HH:mm";
String datetime="11/02 05:01";
DateTime dtDate = DateTime.ParseExact(datetime, dtFormat, culture);

try following code:

DateTime dt = DateTime.ParseExact(your_date, "dd/MM HH:mm" , CultureInfo.InvariantCulture);

this will convert your string into datetime format as per your requirement.

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