I try to parse a date-time stamp from an external system as following:
DateTime expiration;
DateTime.TryParse("2011-04-28T14:00:00", out expiration);
Unfortunately it is not recognized. How can I parse this successfully?
sl3dg3
Specify the exact format you want in DateTime.TryParseExact:
DateTime expiration;
string text = "2011-04-28T14:00:00";
bool success = DateTime.TryParseExact(text,
"yyyy-MM-ddTHH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out expiration);
you can use DateTime.TryParseExact instead.
How to create a .NET DateTime from ISO 8601 format
Try this
DateTime expiration;
DateTime.TryParse("2011-04-28 14:00:00", out expiration);
Without using "T".
You need to append "00000Z" to your string argument.
DateTime.TryParse("2011-04-28T14:00:0000000Z", out expiration);
User DateTime.TryParseExact function as following:
DateTime dateValue;
if (DateTime.TryParseExact(dateString, "yyyy-MM-ddTHH:mm:ss",
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
{
// Do Something ..
}
Read about DateTime.
Related
I am trying to convert a string to a DateTime for some hours now,
The string looks like this
"20140519-140324" and I know its in UTC
I've allready tried this
DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
StartTime.Text = ourDateTime.ToString("g");
and this
DateTime ourDateTime= DateTime.ParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
StartTime.Text = ourDateTime.ToString("g");
but none of these work. What I am not doing properly?
From DateTime.TryParseExact method
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly.
In your example, they are not. Use yyyyMMdd-HHmmss custom format instead which exactly matches with your string.
Here an example on LINQPad;
string s = "20140519-140324";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
dt.Dump();
}
Here a demonstration.
Your DateTime.ParseExact example also won't work because of the same reason.
For more information;
Custom Date and Time Format Strings
You are using the wrong format in the TryParseExact method.
the format parameter should be an indicator to the format of the input string.
therefor you need to do this:
DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
if(success) {
StartTime.Text = ourDateTime.ToString("g");
}
I am getting a string and i want to parse that string as date and want to store it in DataTable.
string can be in formats
1- "2014/23/10"
2- "2014-23-10"
{
string st="2014/23/10";
string st="2014-23-10";
}
And attach time with it.
Any idea to make it possible ?
DateTime.ParseExact or DateTime.TryParseExact are appropriate here - both will accept multiple format strings, which is what you need in this case. Make sure you specify the invariant culture so that no culture-specific settings (such as the default calendar) affect the result:
string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd" };
DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Add date to the DataTable
}
else
{
// Handle parse failure. If this really shouldn't happen,
// use DateTime.ParseExact instead
}
If the input is from a user (and is therefore "expected" to be potentially broken, without that indicating an error anywhere in the the system), you should use TryParseExact. If a failure to parse indicates a significant problem which should simply abort the current operation, use ParseExact instead (it throws an exception on failure).
Since both are not standart date and time format, you can use DateTime.ParseExact method like;
string st = "2014/23/10";
string st1 = "2014-23-10";
var date = DateTime.ParseExact(st,
"yyyy/dd/MM", CultureInfo.InvariantCulture);
var date1 = DateTime.ParseExact(st1,
"yyyy-dd-MM", CultureInfo.InvariantCulture);
Output will be;
10/23/2014 12:00:00 AM
10/23/2014 12:00:00 AM
Here a demonstration.
Of course these outputs depends your current culture thread.
If you want to format your DateTime's as a string representation, you can use DateTime.ToString(string) overload which accepts as a string format.
Since you have more than one format, you can use DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload which is takes your formats as a string array.
var formats = new []{"yyyy-MM-dd", "yyyy/MM/dd"};
DateTime dt;
if(DateTime.TryParseExact(st, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//
}
else
{
//
}
Convert to a DateTime with DateTime.TryParseExact(); or even DateTime.Parse if you need to be flexible. Then you can format it back out however you like!
See: http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Try
DateTime.Parse(st, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Set DateTimeStyles based on your requirement.
Try this:
DateTime.Parse(st);
If It the above line not works for you, then add cultrureInfo below:
DateTime.ParseExact(st,"yyyy/dd/MM", CultureInfo.InvariantCulture);
I am trying to convert the
string date = "31.03.2013"
to a DateTime. Here is my code:
Convert.ToDateTime(date,CultureInfo.InvariantCulture);
I am getting a Format Exception.
According to http://msdn.microsoft.com/en-us/library/vstudio/cc165448.aspx it should work.
Thanks
The invariant culture is based on en-US, where . is not a the date separator.
You need to use the correct culture, such as fr-FR, which does use . as a date separator.
You could also use DateTime.ParseExact or DateTime.TryParseExact with the exact format string.
Convert.ToDateTime("31.03.2013", CultureInfo.GetCultureInfo("fr-FR"))
Or
DateTime.ParseExact("31.03.2013",
"dd.MM.yyyy",
CultureInfo.InvariantCulture)
Will work.
How about
DateTime.ParseExact(date,"dd.MM.yyyy",null);
You could try to use the DateTime.ParseExact method. It should do the trick for you.
DateTime.ParseExact("31.03.2013", "dd.MM.yyyy", CultureInfo.InvariantCulture);
Use this code --
DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
You can try this with DateTime.TryParseExact :
string date = "31.03.2013";
DateTime dateConverted;
DateTime.TryParseExact(date, new string[] { "dd.MM.yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateConverted);
Console.WriteLine(dateConverted);
In earlier vb.net 2008 I used the DateTime to read the date in dd/mm/yy format.
I use to change the culture info to UK format. So that the date will be selected from SQL server as in dd/mm/yy format.
But I know it's not good to play with CultureInfo. Even though I used like the following manner.
Any other better Ideas for me?
Sub Form_Load()
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-GB", False)
End Sub
Any other better Ideas for me? Thanks for the Ideas.
Thanks & Regards.
From DateTime to string:
string s = DateTime.Today.ToString("dd/MM/yyyy");
From string to DateTime:
DateTime d;
bool success = DateTime.TryParseExact("26/05/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
In C# you could get the date string in desired format like,
string date = DateTime.Now.ToString("dd/MM/yyyy");
If you want to get DateTime object from string value representing DateTime in specific culture, you can do
DateTime dt = new DateTime();
DateTime.TryParse("16/01/2011", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"),
System.Globalization.DateTimeStyles.None, out dt);
DateTime --> String
DateTime.Now.ToString( new CultureInfo("fr-FR", false) );
String --> DateTime:
The preferred method would probably be DateTime.Parse()
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
This way you are not changing the Culture info of the current Context. This does assume you know what the format will be beforehand though.
You can format the date using the CultureInfo, without setting the culture for the whole thread, thanks to the IFormatProvider interface:
DateTime d = DateTime.Now;
CultureInfo c = new CultureInfo("en-GB", false);
string s = d.ToString(c.DateTimeFormat);
This has the added advantage that you don't have any hard-coded formats, and if the user changes the localisation settings on their machine, your application will reflect their preferences.
You can use DateTime.TryParse to parse the date...
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}
And even use an IFormatProvider to help TryParse work out the format.
CultureInfo c = new CultureInfo("en-GB", false);
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, c.DateTimeFormat, DateTimeStyles.None, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}
I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
or
DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
More info in the MSDN documentation on ParseExact and TryParseExact.
you could try also TryParseExact for set exact format.
method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx
e.g.
DateTime outDt;
bool blnYYYMMDD =
DateTime.TryParseExact(yourString,"yyyyMMdd"
,CultureInfo.CurrentCulture,DateTimeStyles.None
, out outDt);
I hope i help you.
DateTime.TryParse method
You can also do Convert.ToDateTime
not sure the advantages of either
Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.
Regards...
You can use the TryParse method to check validity and parse at same time.
DateTime output;
string input = "09/23/2008";
if (DateTime.TryParseExact(input,"MM/dd/yy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,"yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))
{
//handle valid date
}
else
{
//handle invalid date
}