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
Related
I have a date string in the following format:
var dateString = Fri Jun 26 2020 00:00:00 GMT+0100 (British Summer Time)
How can I convert this to a DateTime in C# such as 26/06/2020 00:00:00
I have tried:
DateTime.Parse(dateString);
And:
DateTime.ParseExact(dateString);
And I get:
System.FormatException: 'String was not recognized as a valid DateTime.'
You can accomplish this by using DateTime.ParseExact and providing a custom date time format. However, this will only work if you first modify the input string to be able to fit the custom date and time format strings that are included in .net.
CultureInfo provider = CultureInfo.InvariantCulture;
var input = "Fri Jun 26 2020 00:00:00 GMT+0100 (British Summer Time)";
// set up a regex that will match the text starting with GMT, and extract just the timezone offset
// (the description of the timezone is irrelevant here)
var r = new Regex(#"GMT([+-]\d\d\d\d) \([\w\s]*\)");
// this will remove the extra text: "Fri Jun 26 2020 00:00:00 +0100"
// now we can match it in our format string
var s = r.Replace(input, "$1");
var f = "ddd MMM dd yyyy hh:mm:ss zzz"; // matches the s variable
var d = DateTime.ParseExact(s, f, provider); // you now have parsed your date
This will include the timezone offset in the DateTime object. If you just want it to be set to "26/06/2020 00:00:00" and to ignore the datetime offset, then just change the regex replace above to replace with String.Empty instead of $1.
This will solve your problem.
var dateString = "Fri Jun 26 2020 00:00:00 GMT + 0100(British Summer Time)"; Console.WriteLine(DateTime.Parse(dateString.Substring(4, 11)));
Hello so what you can do is you can take advantage of "datetime" class and just write this:
DateTime.Now.ToString("MM/dd/yyyy HH:mm");
edit: sorry i forgot to supply the link haha
https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Date time format from string?
Does anyone know how I could convert the following string to a DateTime value in C# ?
"Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)"
If you only have strings ending with "GMT+0300 (E. Africa Standard Time)", you can try:
string dateString = "Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)";
DateTime date = DateTime.ParseExact(dateString, "ddd MMM dd yyyy HH:mm:ss 'GMT+0300 (E. Africa Standard Time)'", System.Globalization.CultureInfo.InvariantCulture);
The meanings of the specifiers are as follows:
"ddd" The abbreviated name of the day of the week.
"MMM" The abbreviated name of the month.
"dd" The day of the month, from 01 through 31.
"yyyy" The year as a four-digit number.
"HH" The hour, using a 24-hour clock from 00 to 23.
"mm" The minute, from 00 through 59.
"ss" The second, from 00 through 59.
":" The time separator.
"string", 'string' Literal string delimiter.
You can find out more about different format specifiers in the MSDN article named Custom Date and Time Format Strings
Moreover, if you want to parse "GMT+0300 (E. Africa Standard Time)" part too, I think you should implement a way to parse them yourself. I don't think there's a specifier for that.
First of all, you should Africa Standart Time culture info use for yours';
CultureInfo( "af-ZA", false );
But your string is really complex for converting to DateTime. For me it looks imposible to convert to DateTime perfectly. But we can some rehabilitation in your string. For example, if your string was like this; "11/15/2012 00:00:00" you can convert it like this;
using System;
using System.Globalization;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string str = "11/15/2012 00:00:00";
DateTime dt = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", new CultureInfo("af-ZA"));
Console.WriteLine(dt.ToString());
}
}
}
Custom Date and Time Format Strings
DateTime.ParseExact Method
Try this:
DateTime date = DateTime.Parse(yourDateTimeString);
There is no way to handle (E. Africa Standard Time).
Assuming that UTC=GMT you can also get the time zone part, just remove not important parts of your string
string t = Regex.Replace("Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)", "([(].+?[)])", "");
t= t.Replace("GMT", "").Trim();
DateTime a = DateTime.ParseExact(t, "ddd MMM dd yyyy HH:mm:ss zzzz", System.Globalization.CultureInfo.InvariantCulture);
I have a string in format
Jul 13 2011 1:07PM
I want to cast it as
dd/MM/yyyy HH:mm tt
e.g: 13/7/2011 11:49:00 AM //string=Jul 13 2011 1:07PM
I am using following code to cast it to date.
DateTime date = Convert.ToDateTime(Convert.ToDateTime(myDateString).ToString("dd/MM/yyyy HH:mm:ss"));
This works fine if my day in my string is less than 13
Jul 12 2011 1:07PM //this will cast to desire format fine!
Jul 13 2011 1:07PM //gives error String was not recognized as a valid DateTime.
I understand that it is taking day as month but I can not found a way to cast it to desire format.
See DateTime.ParseExact :
DateTime date = DateTime.ParseExact(myDateString, "MMM dd YYYY H:mmtt", CultureInfo.InvariantCulture);
See also Time Format Strings
You should use DateTime.TryParse
DateTime dt ;
if (DateTime.TryParse("Jul 13 2011 1:07PM",out dt))
MessageBox.Show("Converted to Date object");
Post that you use the ToString() method to get the desired output
dt.ToString("dd/MM/yyyy HH:mm")
First, convert the string Jul 13 2011 1:07PM to a date:
var date = Convert.ToDateTime("Jul 13 2011 1:07PM");
Then, convert it to a string in the format you like:
var dateText = date.ToString("dd/MM/yyyy HH:mm:ss");
I believe you're searching for this:
Date.ParseExact("Jul 13 2011 1:07PM", "MMM d yyyy h:mmtt", Globalization.CultureInfo.InvariantCulture)