convert string in a foreign language to date - c#

I have these input:
27 februari 2014
14 maart 2013
7 november 2013
I would like to convert them all to date field as below:
27-02-2014
14-03-2013
17-11-2013
I have tried this method: DateTime enteredDate = DateTime.Parse(s); but it does not work, the error message was:
The string was not recognized as a valid DateTime. There is a unknown
word starting at index 3.

This appears as Dutch, you can parse it by passing new CultureInfo("nl-NL") to DateTime.ParseExact like:
string str = "27 februari 2014";
DateTime dt = DateTime.ParseExact(str, "d MMMM yyyy",
new System.Globalization.CultureInfoCultureInfo("nl-NL"));
Use single d which would consider both single and double digit day part.
To get the formatted output use:
string formattedDate = dt.ToString("dd-MM-yyyy", System.Globalization.CultureInfoCultureInfo.InvariantCulture);

DateTime allows you to provide a CultureInfo, which may be enough for you. If not, and you only get one foreign language, you could simply replace the the words by the correct English ones.

Related

C# Convert dd/MMMM/yyyy to yyyymmdd (Russian)

31 декабря 2016 в 15:10
декабря is not English.
декабря = December
DateTime.Parse("31/December/2016").ToString("yyyymmdd"); => 20161231
DateTime.Parse("31/декабря/2016").ToString("yyyymmdd"); => Error
31 декабря 2016 в 15:10 => 20161231
How do I convert it?
The DateTime format above should be converted using TryParseExact with GetCultureInfo set to Russian culture like this:
String example = "31/декабря/2016"; // December 31, 2016
DateTime result;
bool check;
check = DateTime.TryParseExact(example, "dd/MMMM/yyyy", CultureInfo.GetCultureInfo("ru-RU"), DateTimeStyles.None, out result);
String converted = result.ToString("yyyyMMdd");
Console.WriteLine(check);
Console.WriteLine(converted);
The output returned by console is:
True
20161231
NB: To convert date with spaces instead of slashes between date components, change "dd/MMMM/yyyy" to "dd MMMM yyyy" (use another format to convert time part together).
Working example: .NET Fiddle Demo

String was not recognized as a valid DateTime on DateTime.ParseExact

I know there is a lot of asked question here about DateTime but I saw them all already and seems not to find the right solution for my case.
Here is my code:
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
This is throwing me an Exception.
Here is the value of the variables:
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
You should use format "m/dd/yyyy" because datestring becomes 1/22/2004
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "m/dd/yyyy", new CultureInfo("en-us"));
Unfortunately, both answers are wrong.
So, we all agree your result string will be "1/22/2004". Before looking which formats exactly matches your characters, let's look at your string is a standard date and time format for en-US culture or not.
DateTime.Parse("1/22/2004",
CultureInfo.GetCultureInfo("en-US")) // 22 January 2004 00:00:00
BANG!
We have a DateTime perfectly. But what if our string wouldn't be a standard date and time format for en-US culture? Then we can specify our format with DateTime.TryParseExact method. Let's look at which formats we can use to parsing our string.
1 matches with "M" custom format specifier which is from 1 to 12 and single-digit month is formatted without a leading zero.
/ is a DateSeparator and we can use it the same in our format because en-US culture has / as a DateSeparator already. Remember, "/" custom format specifier has a special meaning of replace me with current culture or supplied culture date separator
22 matches with "dd" custom format string which is from 01 to 31 and single-digit days is formatted with a leading zero. Remember, you can also use d format specifier in such a case but using wider formats is recommended.
2004 matches with "yyyy" custom format specifier which represents the year with a four digits.
So, the right format will be M/dd/yyyy in result.
string s = "1/22/2004";
DateTime dt;
if(DateTime.TryParseExact(s, "M/dd/yyyy", CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt); // 22 January 2004 00:00:00
}
You are referring to wrong format, so obviously it will throw exception. Below is what you are doing
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
string ex = partialDate + dtfi.DateSeparator + _baseDate.ToString();
which gives you 1/22/2014 i.e., MM/dd/yyyy
and in code you are referring to
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
Try using correct Format, to get the right result.

Remove leading zero form month C#

I'm having trouble to remove the leading zero from a date I found this on the miscrosoft website.
DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August
Totally doesn't work here.
This is my code:
string date = '2013-04-01'
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.ToString("M");
Test is now 01 April
I just need it to be 4 in a string or int idc
Thanks!
Edit if I do:
billrunDate.ToString("(M)");
I get (4), but I dont need ()
EDIT 2:
Well this works
string test = billrunDate.ToString(" M ");
string testTwo = test.Trim();
Very very ugly
It's interpreting M as a standard date and time format for "month day pattern".
To interpret a single character pattern as a custom date and time pattern, just prefix it with %:
string test = billrunDate.ToString("%M");
One of my most referenced MSDN pages is the Custom Date & Time Format Strings page. You can use these as part of the formatting passed in to the ToString() method. If any of them are standard formatting patterns (as "M" is) and you want to use them along, you have to preface them with '%' or have a space before or after them in the format string (so use "%M", " M", or "M " instead of "M").
Relevant section:
"M"
The month, from 1 through 12.
"MM"
The month, from 01 through 12.
"MMM"
The abbreviated name of the month.
"MMMM"
The full name of the month.
You don't need to convert to string the date to retrieve the month number.
Just read the Month property of the DateTime class:
string date = "2013-04-01";
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.Month.ToString();

DateTime.TryParseExact CultureInfo.InvariantCulture

Can anyone see what I'm doing wrong, I'm trying to parse the date to ensure its a valid date, if so convert it to the format I require.
I have tried different ways of doing this, but all return 01/01/0001 00:00:00.
value of string parseArrivalDate = 02/02/2013
DateTime ukDateFormat;
string ukFormat = "0:ddd, MMM d, yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
-------------------------------------EDIT-------------------------------
OK sorry, I did not explain it very well. If I enter UK format say 27/02/2013, and when I had UK format as dd/MM/yyyy it worked ok, problem was when I was entering US or any other format, it was returning the incorrect date, so I was changing the format round thinking that was the problem.
It has now dawned on me after reading your comments, that I had the uk format correct 1st time, so my problem is, how can I change the code, so that any date format can be parsed correctly.
Hope that makes more sense
Thanks
Your string
"0:ddd, MMM d, yyyy"
has a number 0, a colon :, and a format corresponding to
"Wed, Mar 27, 2013"
for example, if the culture is "en-GB" ("English (United Kingdom)"). It probably comes from a String.Format, Console.WriteLine or similar method call, where it is put into braces {} to format a text, as in
Console.WriteLine("The date {0:ddd, MMM d, yyyy} was selected.", someDateTime);
It would work with code like:
string arrivalDateString = "Wed, Mar 27, 2013";
...
DateTime result;
string yourFormat = "ddd, MMM d, yyyy"; // no "0:" part
bool isOK = DateTime.TryParseExact(arrivalDateString, yourFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (isOK)
{
// Worked! Answer is in 'result' variable
}
else
{
// Didn't work! 'result' variable holds midnight 1 January 0001
}
The format that corresponds to "27/03/2013" is "dd/MM/yyyy" (or "d/M/yyyy"). The format that corresponds to "03/27/2013" is "MM/dd/yyyy" (or "M/d/yyyy").
It is not possible to have one method that handles both styles of dates, since a string like
"01/04/2013" /* ambiguous */
could mean either
1 April 2013
January 4, 2013
so it's ambiguous, and there's no way we can tell what date is meant. See also Wikipedia: Calendar date → Date format.
your date string is: 02/02/2013 and the format you are using is "0:ddd, MMM d, yyyy" which is wrong, it should be MM/dd/yyyy if its month first.
DateTime ukDateFormat;
string ukFormat = "MM/dd/yyyy";
DateTime.TryParseExact(parseArrivalDate, ukFormat,CultureInfo.InvariantCulture,DateTimeStyles.None, out ukDateFormat);
DateTime test = ukDateFormat;
If the date you have specified contains day first then month, then use the format "dd/MM/yyyy", By the way you can using single d and M for both single digit and double digits day/month.
Currently you are getting the DateTime.MinValue, since parsing is failing because of the invalid format.
I have no idea what you expect, but your input string does not met your ukFormat pattern! So it's totally right behavior.
Change your pattern to ""dd/MM/yyyy"" to make TryParseExact work.
Your provided format looks a little strange. Try to replace it with this
string ukFormat = "dd/MM/yyyy";
And read the documentation on this.
Thanks everyone for helping me understand where I was going wrong, the code below is what I have came up with although not perfect as 03/06/2013 UK is different than the meaning of 03/06/2013 US.
I have added text above the text box asking people to use format dd/mm/yyyy.
string getArrivalDate = ArrivalDate;
string getDepartureDate = DepartureDate;
string dteFormat = "dd/MM/yyyy";
DateTime result;
string arrivalDateParse;
string departureDateParse;
bool arrival = DateTime.TryParseExact(getArrivalDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (arrival)
{
arrivalDateParse = getArrivalDate;
}
else
{
arrivalDateParse = "notvalid";
}
bool depart = DateTime.TryParseExact(getDepartureDate, dteFormat, new CultureInfo("en-GB"), DateTimeStyles.None, out result);
if (depart)
{
departureDateParse = getDepartureDate;
}
else
{
departureDateParse = "notvalid";
}
if (arrivalDateParse == "notvalid" || departureDateParse == "notvalid")
{
if (Request.IsAjaxRequest())
{
return Json(new { Confirm = "Date not in correct format" }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Error"] = "Sorry your arrival date or departure date is not a valid format, please enter date as dd/mm/yyyy example 02/12/2013";
return View("~/Views/Shared/Error.cshtml");
}
If anyone can improve on the code, it would be appreciated.
Thanks
George
Rather than using InvariantCulture for this consider using RoundTrip style (ISO-8601). See this MSDN article: http://msdn.microsoft.com/en-us/library/bb882584.aspx

Getting DateTime in a format with spaces between them not slashes if possible

I am trying to get date in this format
"yyyy MM dd"
with spaces between them not slashes, but its not working
using (SqlDataReader r = sqlComm.ExecuteReader())
{
if (r.Read())
{
DateTime Date
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
I can't make any change to SQL Stored Procedure at all
EDIT
Sorry it was giving me this for above "25 10 2012 10:00:00:00 AM" or something so I don;t think I was doing it properly, I only want date like this "yyyy MM dd"
how about changing \ into space?
.ToString("yyyy MM dd")
Building off of Marc's answer, it seems like you may be a bit confused about how the DateTime object vs. a string representation of the date actually work. The DateTime is just an offset from the starting point.
This line in your code first takes the value from the Date column in your SQL reader, then converts it to a string with the "yyyy/MM/DD" format, then finally turns that string into a DateTime object.
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
So as you can see, you're ending up with a DateTime object, not the display string you want. If you actually want this code to return just a formatted string , this is what your final line should look like:
EDIT
= r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
From date to string
var str= date.ToString("yyyy MM dd")
and for string to date
DateTime date = DateTime.ParseExact(string, "yyyy MM dd", CultureInfo.InvariantCulture);
So you want this format: "yyyy MM dd" but you use this "yyyy/MM/dd".
Instead:
String dateString = r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
look: http://ideone.com/XecnUP
A DateTime does not have a format. It is just the "how long since {epoch}", give-or-take some offset/timezone information. If the value in the source is a datetime, then all you need is:
DateTime date = (DateTime)r["Date"];
Then you might format that later at the UI. But to repeat: a DateTime does not have a format.

Categories