from a file i read a string like this: "Nov 4 07:27:27 2022 GMT". I try to convert this to german Datetime, later it will be stored in a SQL-table.
Currently i do the conversion like this:
MyTmpString = "Nov 4 07:27:27 2022 GMT";
string format;
CultureInfo provider = CultureInfo.InvariantCulture;
format = "MMM d HH:mm:ss yyyy GMT";
try {
Datum_von = DateTime.ParseExact(MyTmpString, format, provider);
Console.WriteLine("{0} converts to {1}.", MyTmpString, Datum_von.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", MyTmpString);
}
This works for that specific case. I already run into problems if day as more than 1 digit. In this case i have to use a format like this:
format = "MMM dd HH:mm:ss yyyy GMT";
May be the string occurs in more variants currently i dont know. i dont want to create a format and try-catch for every possibility. Iam looking for a kind of universal conversionmethod to have a german date at the end.
What should i do here, do you have any recommendations?
Thank you,
Hans
As Hans Kesting suggests, ParseExact's -d format shouldn't care if days are 1 or 2 digits. Your problem is the extra spaces.
Also instead of relying on catching an exception, which is expensive performance-wise, you should use TryParseExact. It even has an option that allows you to ignore superfluous white space in the string:
var myTmpString = "Nov 14 07:27:27 2022 GMT";
// Or var myTmpString = "Nov 4 07:27:27 2022 GMT";
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MMM d HH:mm:ss yyyy GMT";
bool result = DateTime.TryParseExact(myTmpString, format, provider, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out DateTime datum_von);
if (result)
{
Console.WriteLine("{0} converts to {1}.", myTmpString, datum_von.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format.", myTmpString);
}
If TryParseExact returns true, you can use the value from the out parameter, otherwise parsing has failed.
Related
I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.
Suppose my date is
string dat = "11-01-2019"
and I am using
string date = DateTime.Parse(dat).ToString("dd MMM yyyy");
but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue
You'll need to specify the culture the date is formatted for. I'm assuming UK here:
var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
string date = DateTime.Parse(dat, ukCulture).ToString("dd MMM yyyy");
Console.WriteLine(date);
Try it online
Note that you'll get a FormatException if you enter an invalid date here, so it might be better to use TryParse:
var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
DateTime parsedDate;
if (DateTime.TryParse(dat, ukCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
string date = parsedDate.ToString("dd MMM yyyy");
Console.WriteLine(date);
}
else
{
Console.WriteLine("invalid date");
}
Try it online
Adding to John's great answer, here's a list of CultureInfo codes for reference:
http://www.csharp-examples.net/culture-names/
I have list of DateTimes, and I want to get DateTime with some format for show hours minutes seconds. For Example I have 4:32 PM 22 December 2015 from en-US culture and if I use bg-BG then to return 16:32 22 Декември (is mean December) 2015. Well is return 4:32 22 Декември 2015.
This is my simple code.
List<DateTime> xAxises = SetListOfDateTimes();
var culture = Thread.CurrentThread.CurrentCulture;
for (int i = 1; i <= xAxises.Count; i++)
{
string someTime = xAxises.ElementAt(i - 1).ToString("hh:mm:ss tt", Thread.CurrentThread.CurrentCulture = culture);
string anotherTime = xAxises.ElementAt(i - 1).ToString("ddd, dd MMMM hh:mm:ss tt", Thread.CurrentThread.CurrentCulture = culture);
string thirdTime = xAxises.ElementAt(i - 1).ToString("dd MMMM yyyy", Thread.CurrentThread.CurrentCulture = culture);
string fourthTime = xAxises.ElementAt(i - 1).ToString("MMMM yyyy", Thread.CurrentThread.CurrentCulture = culture);
}
My really problem is I have few DateTimes with bg-BG format and in someTime is return in en-US format. When DateTime is 21:22:30 the someTime is show me 9:22:30. I want to be 21:22:30. I put tt because is possible my application to used in United State if is culture in en-US.
Anybody to know how can return DateTime with current culture correctly.
Well, if you say you want 12 hour format, you get it. Try HH instead of hh (see msdn).
Or ToLongTimeString(). There are some more of these, long and short versions of time and `date, at least.
BTW, DateTime.Now.ToLongDateString() gives me Freitag, 5. Februar 2016 without the need to explicitly specify a culture.
If you want to get time string in 24-hours format, you should use time format "HH:mm:ss" in ToString function.
You can read more about date and time formatting here:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
The user is supposed to enter date in format: %m %d %Y
What I need to do is convert the date to: 11 11 2013 ( which is today`s date). I have not worked much with dates. Is there some method that does this conversion out of the box? I looked through DateTime options but couldn't find what I need.
Edit:
From the answers received it seems that it is not very clear what I am asking.
In our software the user can insert dates in format like this:
http://ellislab.com/expressionengine/user-guide/templates/date_variable_formatting.html
I am trying to parse this user input and return the today date. So from the link above:
%m - month - “01” to “12”
%d - day of the month, 2 digits with leading zeros - “01” to “31”
%Y - year, 4 digits - “1999”
I was wondering if there is a method that takes %m %d %Y as an input and returns the corresponding today date in the specified format ( which is 11 11 2013 today). Or at least something close to that.
Hope it is more clear now.
EDIT 2:
After digging a little bit more I found that what I am looking for is an equivalent of C++ strftime in C#.
http://www.cplusplus.com/reference/ctime/strftime/
But for some reason I cannot see an example this to implemented in C#.
You can use DateTime.TryParseExact to parse a string to date and DateTime-ToString to convert it back to string with your desired format:
DateTime parsedDate;
if (DateTime.TryParseExact("11 11 2013", "MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
// parsed successfully, parsedDate is initialized
string result = parsedDate.ToString("MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.Write(result);
}
My go-tos for DateTime Input and Output:
http://www.dotnetperls.com/datetime-parse for input (parsing)
http://www.csharp-examples.net/string-format-datetime/ for output (formatting)
string dateString = "01 01 1992";
string format = "MM dd yyyy";
DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
Edit since his edit makes my above answer irrelevant (but will leave there for reference):
From what you're saying, you want to output today's date in a dynamically-defined format?
So if I want to see month, date, year, I say "MM dd YY" and you return it to me?
If so:
DateTime dt = DateTime.Today; // or initialize it as before, with the parsing (but just a regular DateTime dt = DateTime.Parse() or something quite similar)
Then
String formatString = "MM dd YY";
String.Format("{0:"+ formatString+"}", dt);
Your question is still quite unclear, though.
Use ParseExact:
var date = DateTime.ParseExact("9 1 2009", "M d yyyy", CultureInfo.InvariantCulture);
I want to parse strings with date that can have different formats like:
"21.12.12", "4,12,2011", "30 Jun 11", "16 12 2013" , "April 2013", "12. April 2012", "12, März 2011".
I have this code:
string[] ll = {"en-US", "de-DE"};
date = "4,12,2011";
foreach (string l in ll) {
if (DateTime.TryParse(date, new CultureInfo(l),
DateTimeStyles.None, out pDate)) {
return pDate;//.ToString("dd.MM.yyyy");
}
}
And I have problems with dates like this:
"21.12.12" is parsed like "21 December 2012", and it is OK
"4,12,2011" is parsed like "12 April 2011", it is not OK, I need "4 December 2011"
How to set order for Day and Month?
It must be Day before Month.
To specify the format(s) of the string you are passing, you should use the ParseExact method.
Use DateTime.ParseExact, it has also an overload tha allows to pass a string[[] for all allowed formats.
string[] dates = new[] { "21.12.12", "4,12,2011", "30 Jun 11", "16 12 2013", "April 2013", "12. April 2012", "12, März 2011" };
CultureInfo germanCulture = CultureInfo.CreateSpecificCulture("de-DE"); // you are using german culture
string[] formats = new[] { "dd/MM/yy", "d,MM,yyyy", "dd MMM yy", "dd MM yyyy", "MMMM yyyy", "dd. MMMM yyyy", "dd, MMMM yyyy"};
foreach (string dateString in dates)
{
DateTime dt = DateTime.ParseExact(dateString, formats, germanCulture, DateTimeStyles.None);
Console.WriteLine(dt.ToString());
}
I have used german culture because your date-strings contain german month names. So this code works even if the current culture is different.
All of the test dates that you gave actually parse correctly in the de-DE culture that you specify. The problem comes that you try to parse it in the american culture first where they use mm.dd.yyyy style formats.
The correct solution in general is to always make sure you know what culture you are using when parsing the string rather than guessing. If you have to guess you will get these kinds of problems at times.
In this case though it looks like they are all acceptable de-DE date strings so you can just parse them as that without needing the loop of trying different cultures (which as mentioned is probably never likely to be a perfect result).
According to your code
string[] ll = {"en-US", "de-DE"};
you initially try parse DateTime with "en-US" culture; so the "4,12,2011" will be parsed
as americans do - MM/DD/YYYY - month the first (12 April). Change order in your array
string[] ll = {"de-DE", "en-US"};
and "4,12,2011" will be 4 December
This is specific for the en-US culture. It may be strange for us Europeans, but Americans really write month before day in dates. You may use en-GB instead - it will handle the same names of months and the European order.
I have some date returned from FTP server like this
Aug 28 11:03
Aug 28 18:06
Sep 6 16:03
Im using this code to parse the time
CultureInfo provider = new CultureInfo("en-US");
_fileDateTime = DateTime.ParseExact(timestring, "MMM dd H:mm", provider);
The first two date work, but the last won't. Does any one have better ideas in parsing these kind of date format?
MMM d H:mm will work with Sep 6 16:03 but in my case its Sep 6 16:03 will not work, note the double space between Sep and 6
The first two date work, but the last won't.
That's because you are using dd for date and the last date returned is 6 and not 06. Use Single d. If last date returned was 06 your format would have worked like a charm.
Its should be like
DateTime.ParseExact(timestring, "MMM d H:mm", provider);
There are multiple issues, one is which is already pointed out in other answers i.e. using single d for date since last date is 6 not 06. The other problem with the last date is that it has multiple spaces in between date and month because of that your format which is taking care of dates with single space is not working. You need to first remove the extra space and then parse using format with single d. Try the following code:
string timestring = "Sep 6 16:03";
//string[] array = timestring.Split(" ".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
//timestring = string.Join(" ", array);
timestring = System.Text.RegularExpressions.Regex.Replace(timestring, #"\s+", " ");
CultureInfo provider = new CultureInfo("en-US");
DateTime _fileDateTime = DateTime.ParseExact(timestring, "MMM d H:mm", provider);
Use one d so it expects possible single-digit days (ie, "6" instead of "06").
MMM d H:mm