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
Related
I need to parse to following Date Aug 20 11:38:43 2017 GMT
I'm trying to use DateTime.TryParseExact but can't find the correct format.
my latest format is MMM dd hh:mm:ss yyyy
my code :
string nextUpdate; //Next Update: Aug 20 11:38:43 2017 GMT
string dateTimeFormat = "MMM dd hh:mm:ss yyyy";
DateTime crldt;
DateTime.TryParseExact(nextUpdate.Split(':')[1].Trim(), dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out crldt);
when I run the code I get crldt ~ Date = {1/1/01 12:00:00 AM}
my question : what format should I use or what alternative way can I use to parse this string to DateTime
UPDATE
using suggestions from : #Sergey Berezovskiy
I've updated the code to :
string nextUpdate; // Next Update: Oct 7 06:16:18 2017 GMT
string dateTimeFormat = #"MMM dd HH:mm:ss yyyy \G\M\T";
Regex r =new Regex(".*Next Update:.*");
nextUpdate = r.Match(Crltext).Value;
DateTime crldt;
DateTime.TryParseExact(nextUpdate.Substring(nextUpdate.IndexOf(':')+1).Trim(),
dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out crldt);
int intDTComp = DateTime.Compare(crldt, DT_now);
I've found a date that doesn't fit this format : Next Update: Oct 7 06:16:18 2017 GMT
what is the issue now ?
UPDATE 2
I've found the issue , but can't find a clean solution.
The issue is that the problematic date is Oct 7 ... ,
while the format is MMM dd ...
my workaround is adding another format MMM d hh:mm:ss yyyy and using it if date = {1/1/01 12:00:00 AM}
what other solution may I use in this scenario
First of all, don't forget that your string contains "GMT". You should either remove it from the string, or add to format pattern:
string nextUpdate = "Next Update: Aug 20 11:38:43 2017 GMT";
string format = #"MMM dd hh:mm:ss yyyy \G\M\T";
Next - don't split input string by : because there is another : symbols in the string. And you will get array with parts ["Next Update", " Aug 20 11", "38", "43 2017 GMT"]. Taking the second item from array gives you " Aug 20 11". Instead, you should just take substring after first : occurance:
string s = nextUpdate.Substring(nextUpdate.IndexOf(':') + 1).Trim();
And finally parse that string using your format:
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(s, format, provider, DateTimeStyles.AssumeUniversal);
Output will depend on your time zone. E.g. for my time zone GMT+3 it will be:
8/20/2017 14:38:43
If this is your string:
"Next Update: Aug 20 11:38:43 2017 GMT"
Then when you do this:
nextUpdate.Split(':')[1].Trim()
You get this:
"Aug 20 11"
Which doesn't match your date format. I suspect you don't just want the second split value, but also all remaining split values. You can re-join them. Something like this:
string.Join(":", nextUpdate.Split(':').Skip(1)).Trim()
This would split them by the ":" character, skip the first one but keep all remaining ones, and re-join the remaining ones into another string with the ":" character again.
Note: You may also need to account for that time zone value. There are some helpful ideas on this question for how to do that.
If that's the input, I propose that you take the format exactly as the input
string nextUpdate = "Next Update: Aug 20 11:38:43 2017 GMT";
string dateTimeFormat = #"\N\e\x\t\ \U\p\d\a\t\e\:\ MMM dd hh:mm:ss yyyy\ \G\M\T";
DateTime crldt;
crldt = DateTime.ParseExact(nextUpdate, dateTimeFormat , System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
This way, when reading the code it's very clear what the expected format is, and you don't have code with Split() or other items that need explanation.
Also note that if you leave the colons (:) like that, they may be replaced by .NET to match the hour separator. Use \: if you always require a literal colon.
As I wrote in the comments before, note that you're ignoring the time zone.
Use following code
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime givenDate = DateTime.ParseExact("Aug 20 14:38:43 2017 GMT", "MMM dd HH:mm:ss yyyy GMT", provider); // here HH is for 24 hour format . use hh for 12 hour format
string expectedDate = givenDate.ToString("dd/MM/yy hh:mm:ss tt"); // tt is for AM or PM (no need to use tt if you use hour as HH I mean 24 hour format)
Your Output will be 20/08/17 11:38:43 AM
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.
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
How Can I convert following date string to dateTime:
Fri, 18 Dec 2009 9:38 am PST
I tried DateTime.Parse(string)
I got following error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 25. System.SystemException {System.FormatException}
UPDATE
I tried to get weather from yahoo and I tried to get date like this:
Date = DateTime.Parse(feed.Element(yWeatherNS + "condition").Attribute("date").Value),
I debugged it. date attribute is correct (like above).
Thanks.
I don't think there's anything in the BCL which will parse time zone abbreviations. (They should be avoided where possible anyway, as they can be ambiguous.)
If you don't mind losing the time zone information, you can use something like this:
using System;
using System.Globalization;
static class Test
{
static void Main()
{
string text = "Fri, 18 Dec 2009 9:38 am PST";
DateTime parsed = TrimZoneAndParse(text);
Console.WriteLine(parsed);
}
static DateTime TrimZoneAndParse(string text)
{
int lastSpace = text.LastIndexOf(' ');
if (lastSpace != -1)
{
text = text.Substring(0, lastSpace);
}
return DateTime.ParseExact(text,
"ddd, dd MMM yyyy h:mm tt",
CultureInfo.InvariantCulture);
}
}
Note that that assumes a fixed date/time format and culture. Your needs may vary, and you should also consider using TryParse or TryParseExact if this is user input.
If DateTime.Parse can't figure it out automatically, you can use DateTime.ParseExact where you specify the format being used.
In your case this would be something like, you'll need to replace the 'PST' yourself however:
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "Fri, 18 Dec 2009 9:38 am PST";
dateString = dateString.Replace("PST", "-08:00");
string format = "ddd, dd MMM yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
If your program needs to work with different timezone abbrevations, you'll have to build a Dictionary with abbrevation to time zone offset conversions.
i have this text format:
8/27/2009 8:23:06 AM
Thu Aug 27 12:42:22 2009
08/12/2009 20:22
i need to get this: dd/mm/yyyy
how to do it in C# Winform code ?
thank's in advance
You could parse it with DateTime.Parse(...) and after woods print it with DateTime.ToString().
var date1 = DateTime.Parse("8/27/2009 8:23:06 AM", CultureInfo.GetCultureInfo("en-US"));
var date2 = DateTime.Parse("Thu Aug 27 2009 12:42:22", CultureInfo.GetCultureInfo("en-US")); //Edited the date a little
var date3 = DateTime.Parse("08/12/2009 20:22", CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(date1.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date2.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date3.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Some of it is maybe redundant for you. I live in DK and have DK culture so I can't parse the same strings as you can if you have a US computer. Therefore I have set the culture explicit. If you have US culture by standard or want to adapt the application for other cultures then you can use:
//for parsing
var date1 = DateTime.Parse("A date");
//for printing
date1.ToShortDateString();
As fletcher, you can use DateTime.TryParse instead if you parse user input or data where you expect flaws in the provided date strings.
For those particular formats I would use the DateTime.TryParse function. I 'm pretty sure only the final string you have provided would be accepted by the parse operation, the TryParse function will return a boolean value indicating the success of the operation. Once you have the resulting DateTime object you can then output a string in ShortDate format using the ToShortDateString function or you can specify a different format if you wish.
DateTime date = new DateTime();
bool parseSucceeded = DateTime.TryParse("08/12/2009 20:22", out date);
if(parseSucceeded)
Console.WriteLine(date.ToShortDateString());
DateTime.Parse("text")