Converting "August 2012" to DateTime object with TryParseExact - c#

I am trying to parse a string that is of the format "August 2012" into a DateTime object. The string is coming from the column name in a DataTable.
string columnName= row[col].ToString(); // "August 2012"
Initially I tried using DateTime.TryParse() ...
bool result = DateTime.TryParse(row[col].ToString, out convertedDateTime);
but it kept returning false. So next I tried using DateTime.TryParseExact using the the proper cultureformat as described here ...
CultureInfo enUS = new CultureInfo("af-ZA");
DateTime.TryParseExact(row[col].ToString(), "y", enUS, DateTimeStyles.None, out columnNameAsDate)
However, this keep returning false also. What am I doing wrong? SHouldn't I be able to parse a string in the format August 2012 into a DateTime object?

This should give you the date expected.
string columnName= row[col].ToString(); // ==> August 2012
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate);
First: You should specify the exact culture. In af-ZA culture the eighth month of the year is named "Augustus" not "August" and this will, of course, fail.
Second: You should pass the correct format specification to get the full month name (MMMM) and the year (yyyy).

I would split the string first:
DateTime outDate = new DateTime();
string[] words = columnName.Split(' ');
if(words.Length>1){
string month = words[0].Substring(0,3);
string year = words[1];
outDate = DateTime.ParseExact(month+' '+year,
"MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
}

Related

I'm trying to parse Ukrainian date/time strings from a log file

The dates are recorded as follows in the logs:
08 груд. 2017 00:00:06,694
I've been using Linqpad to try to come up with a valid date time mask using the Ukrainian culture, and this is what I've tried:
var dateString = "08 груд. 2017 00:00:06,694";
DateTime date;
DateTime.TryParseExact(
dateString,
"dd MMMM. yyyy HH:mm:ss,fff",
new CultureInfo("uk-UA"),
DateTimeStyles.None,
out date);
Console.WriteLine(date);
This does not work, and the output from this script is:
1/1/0001 12:00:00 AM
This same approach has worked well for me for several other languages, so I'm puzzled as to what is happening here. As best as I can tell, the month is not being parsed correctly. I've try substituting "hrud." for the month value (from: https://www.loc.gov/aba/pcc/conser/conserhold/Mosabbr.html), but that does not work either.
MMMM format specifier for month means "full month name". You can see what are full month names for given culture with:
var culture = new CultureInfo("uk-UA");
var monthNames = culture.DateTimeFormat.MonthNames;
For this culture, december full name is "грудень", not "груд". You might think to use "short month name" format specifier MMM. You can look "short names" for month for given culture like this:
var culture = new CultureInfo("uk-UA");
var monthNames = culture.DateTimeFormat.AbbreviatedMonthNames;
However you will see that short name for december is "гру" and still not "груд". So to parse your string with default month names for your culture you need to either do:
var dateString = "08 грудень 2017 00:00:06,694";
DateTime date;
DateTime.TryParseExact(dateString, #"dd MMMM yyyy HH:mm:ss,fff", new CultureInfo("uk-UA"), DateTimeStyles.None, out date);
Or
var dateString = "08 гру. 2017 00:00:06,694";
DateTime date;
DateTime.TryParseExact(dateString, #"dd MMM. yyyy HH:mm:ss,fff", new CultureInfo("uk-UA"), DateTimeStyles.None, out date);
Another option is to adjust culture month names for your case, like this (note that it will not modify global culture settings, only month name for this particular CultureInfo instance, so there is no danger in doing this):
var dateString = "08 груд. 2017 00:00:06,694";
DateTime date;
var culture = new CultureInfo("uk-UA");
var defaultShortNames = culture.DateTimeFormat.AbbreviatedMonthNames;
var defaultShortGenitiveNames = culture.DateTimeFormat.AbbreviatedMonthGenitiveNames;
// obviously modify all month names as necessary
defaultShortNames[11] = "Груд";
defaultShortGenitiveNames[11] = "груд";
culture.DateTimeFormat.AbbreviatedMonthNames = defaultShortNames;
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames = defaultShortGenitiveNames;
// store this modified culture and reuse when necessary
// that MMM format consists of 3 letters is irrelevant - it will still
// work fine with abbreviated month names of 4 characters or more
DateTime.TryParseExact(dateString, #"dd MMM. yyyy HH:mm:ss,fff", culture, DateTimeStyles.None, out date);
As others have mentioned, MMMM is the full month name and MMM is the three-character abbreviated month name, so neither will work out of the box. Rather than hard-code month names or modify the CultureInfo, I'd prefer to pre-process the string to truncate the month to the 3 characters parseable with the MMM custom format string, either with regular expressions (heavyweight) or directly:
var sb = new StringBuilder (date.Length) ;
var nc = 0 ;
foreach (var ch in date)
{
if (char.IsLetter (ch) && nc++ >= 3) continue ;
sb.Append (ch) ;
}
return DateTime.ParseExact ("dd MMM. yyyy HH:mm:ss,fff", ...) ;

DateTime format conversion mm/dd/yyyy to yyyy/mm/dd

Can someone please let me know how do I convert this datetime format into yyyyMMdd
2/28/2017 12:02:04 AM
At the output I should get 20170228
Any advice on this?
If you already have the DateTime as an object
string formattedDate = date.ToString("yyyyMMdd");
If you need to parse the value first.
string dateValue = "2/28/2017 12:02:04 AM";
string format = "M/d/yyyy hh:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateValue, format,
System.Globalization.CultureInfo.InvariantCulture);
For reference you can find a breakdown of the Custom Date and Time Format Strings
You need to specify the format of the date.
If you want it for the current time you can try like this :
string dtime = DateTime.Now.ToString("yyyy/MM/dd");
This is the solution I have come up with for you:
string format = "M/d/yyyy hh:mm:ss tt";
string dateString = "2/28/2017 12:02:04 AM";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(dateString, format, provider);
string output = date.ToString("yyyyMMdd");
If you're using C# 6 or later (VS2015), you can format DateTime objects easily by using string interpolation using a custom format string. The custom format string that you're looking for is "yyyyMMdd".
// create your preferred date and time in a new DateTime struct
DateTime yourDateTime = new DateTime(2017, 2, 28, 0, 2, 4);
// format yourDateTime as a string
string yourFormattedDateTime = $"{yourDateTime:yyyyMMdd}";
You can read more about interpolated strings at https://msdn.microsoft.com/en-us/library/dn961160.aspx, and, as previously mentioned by #Adam Carr, you can find more information on custom date and time format strings at https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

DateTime.ParseExact And making it work with a custom format

I have a datetime coming back from an text file as a string in the format:
Saturday 15-07-2016 00:55:54
as in
"dddd dd-MM-yyyy HH:mm:ss"
I am trying to convert it to DateTime format using the DateTime.ParseExact, my code is as following:
CultureInfo provider = CultureInfo.InvariantCulture;
string lastLine = File.ReadLines("logon.txt").Last(); //the date string is in the logon.txt
DateTime dt = DateTime.ParseExact(lastLine, "dddd dd-MM-yyyy HH:mm:ss",provider);
return dt;
the exception i get is a System.FormatException : {"String was not recognized as a valid DateTime."}
link to logon txt : https://drive.google.com/file/d/0B1oTQq97VF44Z21pT2FzM01XbU0/view?usp=sharing
any ideas?
The problem is that the date you're showing is Friday, but the string says it should be Saturday. Change the content of the file so instead of "Saturday" it says "Friday" and it should work. It does for me, anyway.
Alternatively, you could change the date part to "16-07-2016" and leave the day of the week "Saturday". Either way it should work.
Here's the code that works for me:
CultureInfo provider = CultureInfo.InvariantCulture;
string lastLine = "Friday 15-07-2016 00:55:54";
DateTime dt = DateTime.ParseExact(lastLine, "dddd dd-MM-yyyy HH:mm:ss", provider);
Console.WriteLine(dt);
It prints out:
7/15/2016 12:55:54 AM

How do I convert a string value of date like Mon, 5/5/2014 to datetime dd/MM/yyyy?

Right now I'm using the method stated below and it displays the result in this manner 1/1/0001 12:00:00 AM
string date = "Mon, 15/05/2014";
DateTime alertedDate;
DateTime.TryParseExact(date, new string[] { "ddd, dd/MM/yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out alertedDate);
txtDate.Text = Convert.ToString(alertedDate);
What seems to be the problem here?
Also, my database date value stores the data in MM/dd/YYYY format and my Globalization.CultureInfo is in UK format which is dd/MM/yyyy. Could this cause the error
Change your code to :
string date = "Thu, 15/05/2014";
15/5/2014 is Thursday.
Try
txtDate.Text = alertedDate.ToString("s")
Try this:
string[] formats= { "dd/MM/yyyy" };
string date = "Mon, 15/05/2014";
DateTime dateTime = DateTime.ParseExact(date, formats, new CultureInfo("en-US"), DateTimeStyles.None);
Reference: Example

c# convert string to date type

I've got this string:
string date = "Sun, 17 Mar 2013 12:40:23 +0000";
And trying to convert to a date type but I keep getting a not in correct format error when I try the convert.
DateTime dt = Convert.ToDateTime(date);
And then trying to get it into these formats:
dt.ToString("dd")
dt.ToString("MMMM")
dt.ToString("yyyy")
You can use DateTime.ParseExact for the conversion.
Try the following code:
var date = "Sun, 17 Mar 2013 12:40:23 +0000";
var dt = DateTime.ParseExact(date, "ddd, dd MMM yyyy hh:mm:ss zzz", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("dd"));
Console.WriteLine(dt.ToString("MMMM"));
Console.WriteLine(dt.ToString("yyyy"));
Output:
17
March
2013
Try DateTime.TryParse() or DateTime.Parse()
Try using DateTime.Parse instead.
var dt = DateTime.Parse(date);
I would also recommend that you Parse the date using DateTime.TryParse to make sure that the date is always in a valid format.
DateTime result;
if (DateTime.TryParse(date, out result))
{
Console.WriteLine(result.ToString("dd"));
Console.WriteLine(result.ToString("MMMM"));
Console.WriteLine(result.ToString("yyyy"));
}
else
{
Console.WriteLine("Error parsing date.");
}
If you are still experiencing issues you may need to provide DateTime with a CultureInfo. This allows you to specify the exact Culture used by the parser, to ensure that the computer region settings doesn't cause any issues.
DateTime.Parse(date, new CultureInfo("en-US")); // Specific culture
DateTime.Parse(date, CultureInfo.InvariantCulture); // Culture-insensitive
// Culture-insensitive TryParse
if (DateTime.TryParse(date, out result, CultureInfo.InvariantCulture))
{...}
The normal DateTime uses the culture set by your Operating System.
You can use DateTime.Parse with CultureInfo.InvariantCulture which ignores your current culture, hence avoids possible localization issues.
DateTime dt = DateTime.Parse(date, CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is similar to the english culture and works with your string.
Demo
Have you checked DateTime.TryParse method? If you scroll down, you will notice that the last sample actually is "Fri, 15 May 2009 20:10:57 GMT", similar to your request.
You can use DateTime.Parse() method like;
string date = "Sun, 17 Mar 2013 12:40:23 +0000";
DateTime dt = DateTime.Parse(date, CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("dd"));
Console.WriteLine(dt.ToString("MMMM"));
Console.WriteLine(dt.ToString("yyyy"));
Output will be;
17
March
2013
Here is a DEMO.
Well..If you need the result in numeric format,try as shown below
string date = "Sun, 17 Mar 2013 12:40:23 +0000";
DateTime dt = Convert.ToDateTime(date);
var day = dt.Day;
var month = dt.Month;
var year = dt.Year;
var time = dt.ToShortTimeString();
var hour = dt.Hour;
var minute = dt.Minute;
var second = dt.Second;
The Variables will return the exact numerical form.
NB: Hour will be depicted as 24 hour format
public string dateConvertion(string da)
{
string sDate = da;
sDate = sDate.Replace("-", "/");
sDate = sDate.Replace(".", "/");
string format = "dd/MM/yyyy";
DateTime dDate;
if (DateTime.TryParse(sDate, out dDate))
{
//if (DateTime.TryParseExact(sDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate))
//{
sDate = dDate.ToString("MM/dd/yyyy");
sDate = sDate.Replace("-", "/");
sDate = sDate.Replace(".", "/");
}
return sDate;
}

Categories

Resources