Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 329 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting a String to DateTime

#1
How do you convert a string such as `2009-05-08 14:40:52,531` into a `DateTime`?
Reply

#2
You have basically two options for this. `DateTime.Parse()` and `DateTime.ParseExact()`.

The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.

ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.

You can parse user input like this:

DateTime enteredDate = DateTime.Parse(enteredString);

If you have a specific format for the string, you should use the other method:

DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);

`"d"` stands for the short date pattern (see [MSDN for more info][1]) and `null` specifies that the current culture should be used for parsing the string.


[1]:

[To see links please register here]

Reply

#3
string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);

//////// this methods convert string value to datetime
///////// in order to print date

Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
Reply

#4
Try the below, where strDate is your date in 'MM/dd/yyyy' format

var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
Reply

#5
You could also use DateTime.TryParseExact() as below if you are unsure of the input value.

DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
Reply

#6
try this

DateTime myDate = DateTime.Parse(dateString);

a better way would be this:

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through