converting messy date string to dateTime object in c# - c#

How can I convert the String 20120313 to a DateTime object that holds the value 13-Mar-2012?
I fetch it as
DataEffectiveDate = Convert.ToDateTime(reader["date_id"]);
But it fails here already (converting to 1/1/2001)

You need to use DateTime.ParseExact:
DateTime date = DateTime.ParseExact(text, "yyyyMMdd",
CultureInfo.InvariantCulture);
Then if you want it as "13-Mar-2012", you need:
string reformatted = date.ToString("dd-MMM-yyyy");
... optionally passing in whatever culture you want to use for the month names etc.
(Another alternative is to use my Noda Time, which allows you to parse this as just a local date, without any concerns about what time it will use, time zones etc.)

When you have a particular format in mind, ParseExact is helpful:
string s = "20120313";
var when = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);
There's also an overload that accepts multiple candidate formats.

Try DateTime.ParseExact:
string date = DateTime.ParseExact(reader["date_id"], "yyyyMMdd", new CultureInfo("en"));

Related

String Date To convert DateTime using ParseExact

I have a string and it comes as a DD/MM/YYYY style.(eg : 11/07/2018)
I need to convert this To DateTime format and YYYY-MM-DD style.
I tried it using DateTime.Parse but can't
if (!String.IsNullOrEmpty(fromDate))
{
frm = DateTime.ParseExact(fromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
else if(!String.IsNullOrEmpty(toDate))
{
todt = DateTime.ParseExact(toDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
You can do this in one line of code.
var newDateString = DateTime.ParseExact(myDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyy-MM-dd");
Keep in mind that a DateTime instance is a data structure that does not have a format. When dealing with dates and times it is best to only revert to a human readable string when you need to present/output the value for a human to read. For anything else including persistence to a storage system that supports types (like a relational database) leave the value as a DateTime type.
Example: If you wanted yyyy-MM-dd because you wanted to persist this to Sql Server then you should stop after the parsing (and not call ToString). You can then assign the DateTime instance to a command parameter's Value property directly.
Convert using ParseExact and then use ToString to the target format:
string dateS = "30/04/2018";
DateTime dateD = DateTime.ParseExact(dateS, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string dateS2 = dateD.ToString("yyyy-MM-dd");
Here is a working example in fiddle: https://dotnetfiddle.net/e0yuZ6

Convert string into mm/dd/yyyy format

I have following strings in different formats:
16/05/2014
21-Jun-2014
2014-05-16
16-05-2014
5/19/2014
14 May 2014
I need to convert all the above strings into mm/dd/yyyy format in c#.
I have tried used DateTime.ParseExact as DateTime dt = DateTime.ParseExact("16-05-2014", "mm/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) in C# but i am getting the exception as "String was not recognized as a valid DateTime".
I have also tried to use to Convert.ToDateTime() but it is also not working.
Is there any method or function that we can write/available in C# that would convert the above string formats into a single date format i.e into "mm/dd/yyyy" format ??
Any help on this would be greatly appreciated.
It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.
You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:
string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.
Your main problem is that your format string is wrong. A small m is for minute, a big M is for month.
Try to pass all your formats in an array. For example like this
DateTime.ParseExact("16-05-2014",
new[] {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"},
CultureInfo.InvariantCulture, DateTimeStyles.None);
With this you can parse all your formats at once.
For more information about the format settings, see the official docs.
Few things:
Your input date 16/05/2014 doesn't match your format Month/Day/Year - how can there be a 16th month?
Secondly, you're using mm which represents Minutes, not Months. You should use MM.
Finally, your sample string 16-05-2014 doesn't match the format provided, you've used hyphens - instead of forward slashes /
Supply a collection of different formats matching your input:
string[] formats = new [] { "MM/dd/yyyy", "dd-MMM-yyyy",
"yyyy-MM-dd", "dd-MM-yyyy", "dd MMM yyyy" };
DateTime dt = DateTime.ParseExact("05-16-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
You might find the following method useful to accept whatever date format you want and convert it to DateTime:
public DateTime? DTNullable(string DateTimestring, string CurrDateTimeFormat)
{
if (string.IsNullOrEmpty(DateTimestring)) return null;
else
{
DateTime datetimeNotNull;
DateTime.TryParseExact(DateTimestring, CurrDateTimeFormat, null, System.Globalization.DateTimeStyles.None, out datetimeNotNull);
return datetimeNotNull;
}
}
Pass in your desired string to be converted to DateTime along with it's current date time format and this would return you a nullable DateTime. If you're certain that whatever string you're passing in won't be null then you can remove that bit. The reason for it being there is that you can't convert a null to DateTime. In my case I couldn't be certain if it would be or not so I needed the ability to capture nulls as well.
You can use it like this:
DateTime? MyDateTime = DTNullable(MyStartDate, "dd/MM/yyyy");
If you wanted you could alter the method to accept an array of strings and simply iterate through each and return them all in a list if they were of the same format.
As others have pointed out, months are MM not mm (minutes).
On a DateTime object you can call .ToString("MM/dd/yyyy"). Given the strings you have, you can first create new DateTime objects for each string and then call .ToString("MM/dd/yyyy"). For example:
var dateAsMmDdYyyy = DateTime.Now.ToString("MM/dd/yyyy");

String to Date parsing

I am getting a string and i want to parse that string as date and want to store it in DataTable.
string can be in formats
1- "2014/23/10"
2- "2014-23-10"
{
string st="2014/23/10";
string st="2014-23-10";
}
And attach time with it.
Any idea to make it possible ?
DateTime.ParseExact or DateTime.TryParseExact are appropriate here - both will accept multiple format strings, which is what you need in this case. Make sure you specify the invariant culture so that no culture-specific settings (such as the default calendar) affect the result:
string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd" };
DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Add date to the DataTable
}
else
{
// Handle parse failure. If this really shouldn't happen,
// use DateTime.ParseExact instead
}
If the input is from a user (and is therefore "expected" to be potentially broken, without that indicating an error anywhere in the the system), you should use TryParseExact. If a failure to parse indicates a significant problem which should simply abort the current operation, use ParseExact instead (it throws an exception on failure).
Since both are not standart date and time format, you can use DateTime.ParseExact method like;
string st = "2014/23/10";
string st1 = "2014-23-10";
var date = DateTime.ParseExact(st,
"yyyy/dd/MM", CultureInfo.InvariantCulture);
var date1 = DateTime.ParseExact(st1,
"yyyy-dd-MM", CultureInfo.InvariantCulture);
Output will be;
10/23/2014 12:00:00 AM
10/23/2014 12:00:00 AM
Here a demonstration.
Of course these outputs depends your current culture thread.
If you want to format your DateTime's as a string representation, you can use DateTime.ToString(string) overload which accepts as a string format.
Since you have more than one format, you can use DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload which is takes your formats as a string array.
var formats = new []{"yyyy-MM-dd", "yyyy/MM/dd"};
DateTime dt;
if(DateTime.TryParseExact(st, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//
}
else
{
//
}
Convert to a DateTime with DateTime.TryParseExact(); or even DateTime.Parse if you need to be flexible. Then you can format it back out however you like!
See: http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Try
DateTime.Parse(st, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Set DateTimeStyles based on your requirement.
Try this:
DateTime.Parse(st);
If It the above line not works for you, then add cultrureInfo below:
DateTime.ParseExact(st,"yyyy/dd/MM", CultureInfo.InvariantCulture);

DateTime - How can i account for different delimiter characters

My application is taking the time now, formatting it into a string, and parsing it back to a valid DateTime value using ParseExact. See below for more details:
DateTime dt = DateTime.Now;
DateTime timeNow = DateTime.Now;
string timeStamp = dt.ToString("MM/dd/yyyy HH:mm:ss");
// To match different countries
if (timeStamp.IndexOf("/") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
else if (timeStamp.IndexOf(".") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM.dd.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
Different countries use different date formats. Is there a way to make my application automatically take into account the different formats, rather than having to make a condition for each one that appears?
Thanks for any help,
Evan
If your application is using a string representation for dates internally, I would suggest using the Sortable format specifier when outputting it. That way, you always know that you can read it back using ParseExact and the "s" format specifier.
The only time you should output dates in any other format is when you need to display them for the user, or when some other program requires them in a particular format.
As #Mike Christensen pointed out in his comment, different locales will interpret dates differently. The default output for many European countries is DD/MM/YYYY, whereas in the U.S. it's usually MM/DD/YYYY. If you take the different locales into account, then there will be ambiguity.
You can pass an array of format specifiers with as many formats as you want to support.
string[] formats = new [] { "MM/dd/yyyy HH:mm:ss", "MM.dd.yyyy HH:mm:ss" };
DateTime d = DateTime.ParseExact
(
timestamp, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
However, since you say you are generating the strings yourself, why don't you just make sure you always format them using the InvariantCulture:
string timestamp = dt.ToString("MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);

How do I convert a short date string back to a DateTime object?

I have 2 DateTime objects, which I save to a file after using the ToShortDateString() function; the strings look like "12/15/2009". I am stuck on this part now, I want to initialize DateTime object(s) with these strings so I can compare the timespan between the date dates. Any help appreciated.
You can try
DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);
Have a look at
DateTime.ParseExact Method (String,
String, IFormatProvider)
Easy String to DateTime, DateTime to
String and Formatting
Assuming you're reading back the dates from the file in string format
string date1 = "28/12/2009"; //this will be from your file
string date2 = "29/12/2009"; //this will be from your file
DateTime d1 = DateTime.ParseExact(date1,"dd/MM/yyyy", null);
DateTime d2 = DateTime.ParseExact(date2, "dd/MM/yyyy", null);
TimeSpan t1 = d2.Subtract(d1);
Did you try DateTime.Parse(str)?
I usually try to stick to this when dealing with DateTime/string transitions:
When persisting dates in a text format, format it explicitly. Preferably to a standardized format (such as ISO 8601).
When reading the date back, parse it to a DateTime object using the same, explicitly defined format.
This way your code will not fail when used in places where the date format differs from yours, or if the file is created on one locale, and then parsed in another.
private static string DateToString(DateTime input)
{
return input.ToString("yyyy-MM-dd");
}
private static DateTime StringToDate(string input)
{
return DateTime.ParseExact(input, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
Extract year, month and day, and than use smth like:
var dt = new DateTime(Year,Month,Day)
or crete an extension method to convert back to dateTime this kind of strings, but in general the body of that extension methad would be smth like this.

Categories

Resources