Parse string value to datetime value - c#

I need to parse string value to date time value, I have date in this format:
DD.MM.YYYY
I want to parse value in this format:
YYYY-MM-DD
I tried to do it like this:
DateTime.ParseExact(date_req, "yyyy-MM-dd", CultureInfo.InvariantCulture);
But i have an error: String was not recognized as a valid DateTime.
Is there a way to do this?

If you have a string in the format DD.MM.YYYY why are you passing YYYY-MM-DD to your ParseExact function?
Try like this:
string dateStr = "12.06.2012";
DateTime date = DateTime.ParseExact(dateStr, "dd.MM.yyyy", CultureInfo.InvariantCulture);
Then when you want to output this DateTime instance somewhere you could use the YYYY-MM-DD format, like this:
string result = date.ToString("yyyy-MM-dd");

I think what you want to do is parse your dd.MM.yyyy and then display it as yyyy-MM-dd.
You first have to parse the string into a DateTime:
DateTime date = DateTime.ParseExact(date_req, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Now date is a representation of the date that the computer actually understands (before it was just a string). You can now display this object anyway you want:
string yyyyMMdd = date.ToString("yyyy-MM-dd");
string arabic = date.ToString("yyyy-MM-dd", new CultureInfo("ar"));
// and so on
Don't forget that when converting dates from strings to DateTime and back, culture and time zones are worth keeping in mind.

When parsing a date you need to specify the format you want to read, not the format you want as output later.
So use dd.MM.yyyy as argument to ParseExact.

Check DateTime.ParseExact Method (String, String,
IFormatProvider) Converts the specified string representation
of a date and time to its DateTime equivalent. The format of the
string representation must match a specified format exactly or an
exception is thrown.
you have to specify format string as DD.MM.YYYY rather than "yyyy-MM-dd".
try this:
DateTime dateValue = DateTime.ParseExact(date_req, "DD.MM.YYYY", CultureInfo.InvariantCulture );
// use this when you need to show that formatted date value
string formattedDate = dateValue.ToString("yyyy-MM-dd");
Better way is that use DateTime.TryParseExact Method, if you want it as date rather than string modify your culture info and date separator.
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "05.01.2009";
if (DateTime.TryParseExact(dateString, "DD.MM.YYYY", enUS,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
else
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

First parse it in the existing format then convert to the string format you want.
var date = DateTime.ParseExact(date_req, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var str = date.ToString("yyyy-MM-dd");

You can first convert it to a character array. then you can parse day/month/year separately to integers . You know the indexes of the numbers so this will be easy. after that you can concatenate every element in the way you like.

Error. You have a cake and you want to eat a stake. In order to convince your stomach that that the cake is a stake you have to transform the cake to a stake. This cannot be done. Parsing is about accepting a value as it comes and use a pattern (or more) to translate it to something else and not transform it. So what you want may be right but you ask is wrong.

Related

c# convert string to DateTime format

I am reading a string value from DataTable which is in the format :
"3/29/2022 6:32:05 PM"
How do I convert this string in this format:
"03292022"
I tried this:
string format= "MMddyyyy";
string dateString = "3/29/2022 6:32:05 PM";
DateTime dateValue;
if (DateTime.TryParseExact(dateString, format,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
Here is a working example
string input = "3/29/2022 6:32:05 PM";
string output = DateTime.Parse(input).ToString("MMddyyyy");
Console.WriteLine(output);
You can use DateTime.Parse method to parse the input string into a DateTime object, and then use the ToString method to format the DateTime object as a string with the format "MMddyyyy".
More details can be found here
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring#remarks
You must first parse the date from the original format:
if (DateTime.TryParseExact(dateString, "M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
The "Exact" in ParseExact() isn't just for show: the format string here must be perfect, including single vs double letters for date parts like month, as well as upper-case vs lower-case for date parts like hour. In spite of this, it's usually preferrable to provide the format for ParseExact() over the easier Parse(), which opens you up issues around inferring the cultural settings.
Then you can output the date in the desired format:
Console.WriteLine($"Converted '{dateString}' to {dateValue:MMddyyyy}.");
Remember DateTime values themselves do not have any human-readable format, so you have to specify the format again every time you output it or convert it back to a string. Also remember cultural/internationalization issues mean these conversions are far slower and more error-prone than you'd expect: something to avoid. The general practice is to get a value into a Date or numeric type as quickly as possible, and then keep it there as long as possible, only formatting for output when absolutely necessary.

How to convert string to given date format

The below code is in MM/DD/YYYY format
string dateStr="9/7/1986";
But i want to change it like below format
dateStr="09/07/1986";
again same in MM/DD/YYYY format
This code should work for you.
string dateStr = "9/7/1986";
string newDateStr= DateTime.Parse(dateStr).ToString("MM/dd/yyyy");
newDateStr will hold the value you need.
The best thing to do would be to use that format when you first convert the DateTime value to a string. Although, this would only work if you had it as a DateTime variable first.
You could parse it to a DateTime then format it back to a string.
dateStr = DateTime.ParseExact(dateStr, "M/d/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy");
Note that you'll get exceptions if the string doesn't match the M/d/yyyy format.

How to set/know DateTime class date format interpretion?

I have a particular loop where DateTime instances are to be generated. My problem is on how does the class interpret the input string.
The incoming input strings are of the format MM/dd/yyyy.
Suppose I have "1/17/2014", DateTime would interpret this as MM/dd/yyyy.
But if I have "6/5/2014", how will I be sure that DateTime will parse this with the format MM/dd/yyyy and not dd/MM/yyyy?
EDIT: Inputs may come with the month and/or day in one- or two-digit format.
Because the dates could come in either MM/dd/yyyy or M/d/yyyy then the overload that takes a string[] is the most appropriate:
var dt = DateTime.ParseExact(input,
new[] { "M/d/yyyy", "MM/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Now, regardless of the zero-padding it will work as expected.
Use the ParseExact function to specify the format :
DateTime d = DateTime.ParseExact("6/5/2014", "M/d/yyyy", CultureInfo.InvariantCulture);
If your input are in MM/dd/yyyy format, you will get 06/05/2014 instead of 6/5/2014. You will then have to use :
DateTime d = DateTime.ParseExact("06/05/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture);
Be sure of your input format if you don't want to have an exception.
take a look at DateTime.ParseExact, which will allow you to specifically match the string

How to Convert a Date String with Format "dd/MM/yyyy" to OS Current Culture Date Format

A string has the value in "dd/MM/yyyy" format like "04/10/2012". This should be converted to a Date w.r.t Current Culture of OS.
I have tried below string with Korean as Current Culture of OS in which date format is yyyy-MM-dd, my code is not getting correct Month value, it interchange the month value with day:
Input: "04/10/2012"
Output: 2012-04-10
Code:
DateTime DT;
string dt = "04/10/2012";
DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());
How I can fix that ?
It looks to me like you need to parse it with a fixed format, I think you are currently parsing it with a format other than "dd/MM/yyyy" and because the date is ambiguous (as in, month and day can be interchanged without causing invalid dates) the format is simply switching the month and day value. When you then go to output it, it looks reversed.
Use DateTime.ParseExact to force the parsing format and then use the built-in current culture sensitive string output methods on DateTime to get a formatted string:
var date = DateTime.ParseExact("04/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + date.ToShortDateString()); // Assumes current culture is controlling format
Since your input string is in a fixed format, you should parse it in that format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
If you string has the format dd/MM/yyyy then you have to use DateTime.ParseExact with the specified format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Anything else will try an interpret the string according to the current culture's rules - which, as you have found, will fail.
why not use ToShortDateTimeString()

How to parse string into date time format?

I have string having value "August-25-2011". How can I parse that into Datetime format?
Try:
DateTime dt = DateTime.ParseExact(
your_date,
"MMMM-dd-yyyy" ,
CultureInfo.InvariantCulture);
Try this out.
var date = DateTime.Parse("August-25-2011");
DateTime.ParseExact(
your_date,
"MMMM-dd-yyyy" ,
CultureInfo.InvariantCulture);
For TryParseExact
DateTime parsedDate;
string pattern = "MMMM-dd-yyyy" ;
DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate)
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified array of formats,
culture-specific format information, and style. The format of the
string representation must match at least one of the specified formats
exactly. The method returns a value that indicates whether the
conversion succeeded.

Categories

Resources