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");
}
Related
I have been trying to convert this string to a DateTime object in C#
2019-09-23T08:34:00UTC+1
I've tried using DateTime.Parse but it is throwing an exception for
"String was not recognized as a valid DateTime."
I'm sorry but you seem like a victim of garbage in, garbage out.
That's an unusual format, that's why before I suggest a solution for you, first thing I want to say is "Fix your input first if you can".
Let's say you can't fix your input, then you need to consider a few things;
First of all, if your string has some parts like UTC and/or GMT, there is no custom date and time format specifier to parse them. That's why you need to escape them as a string literal. See this question for more details.
Second, your +1 part looks like a UTC Offset value. The "z" custom format specifier is what you need for parse it but be careful, this format specifier is not recommended for use with DateTime values since it doesn't reflect the value of an instance's Kind property.
As a solution for DateTime, you can parse it like I would suggest;
var s = "2019-09-23T08:34:00UTC+1";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
Console.WriteLine(dt);
}
which gives you 2019-09-23 07:34:00 as a DateTime and which has Utc as a Kind property.
As a solution for DateTimeOffset - since your string has a UTC Offset value you should consider to parse with this rather than Datetime
-, as Matt commented, you can use it's .DateTime property to get it's data like;
var s = "2019-09-23T08:34:00UTC+1";
DateTimeOffset dto;
if(DateTimeOffset.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto.DateTime);
}
which gives you the same result DateTime but Unspecified as a .Kind property.
But, again, I strongly suggest you to fix your input first.
Use TryParseExact to convert the string to datetime. Here is the sample code to covert the given format(s) to datetime
private static DateTime ParseDate(string providedDate) {
DateTime validDate;
string[] formats = {
"yyyy-MM-ddTHH:mm:ss"
};
var dateFormatIsValid = DateTime.TryParseExact(
providedDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out validDate);
return dateFormatIsValid ? validDate: DateTime.MinValue;
}
Then, use this function to convert the string. I am replacing UTC+1 to empty string
static void Main(string[] args) {
string strdatetime = "2019-09-23T08:34:00UTC+1";
DateTime dateTime = ParseDate(strdatetime.Replace("UTC+1", ""));
Console.WriteLine(dateTime);
}
I have date values that are formatted like this: 1/1/2015.
These are produced by a Web Service which I cannot change:
How do I Format this: 1/1/2015 to 01/01/2015, with the leading zero?
Tried this:
Console.WriteLine(String.Format("{0:[##/##/####]}", "1/1/2015"));
And this:
Console.WriteLine(String.Format("{0:MM/dd/yyyy}", "1/1/2015"));
But I get the same formatted output.
I have date values that are formatted like this
In .NET, a DateTime does not have any implicit format. It just have date and time values. Textual representation (aka string representation) of a DateTime can have a format.
If you have string like that, parse it to Datetime and get it's string representation with dd/MM/yyyy format.
string s = "1/1/2015";
DateTime dt;
if(DateTime.TryParseExact(s, "d/M/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Dump(); // 01/01/2015
}
You can try like this:
return yourDateTimeValue.ToString("MM/dd/yyyy");
Edit:
Since you are storing your date as string then try like this:
string s = "1/1/2015";
DateTime dt =
DateTime.ParseExact(s, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Convert the date string into DateTime then get it as MM/dd/yyyy or whatever format you want.
DateTime.Parse("1/1/2015").ToString("MM/dd/yyyy");
How can I convert a string such as 07/26/13 into a C# DateTime variable in the following format? 2013-07-26 00:00:00 (Mysql datetime)
If your CurrentCulture has MM/dd/yy as a standard date and time format, you can just use DateTime.Parse method like;
DateTime date = DateTime.Parse("07/26/13");
If it is not, you can use DateTime.ParseExact or DateTime.TryParseExact methods to parse your string with custom date and time format like;
string s = "07/26/13";
DateTime date;
if(DateTime.TryParseExact(s, "MM/dd/yy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
DateTime doesn't have any implicit format. It has just date and time values. String representations of it have formats. You can format your DateTime with .ToString method like;
date.ToString("yyyy-MM-dd HH:mm:ss");
And by the way, if you want to insert a DateTime value to your database, you shouldn't insert it as a string. You should use parameterized queries and pass your DateTime value to directly to your parameter.
Use TryParseExact.Before posting a question try it yourself
string date_time = "07/26/13";
DateTime d;
if (DateTime.TryParseExact(date_time, "mm/dd/yy", new CultureInfo("en-US"),
DateTimeStyles.None,
out d))
{
date_time = d.ToString("yyyy-mm-dd hh:mm:ss");
}
I have a date which comes in a string like so:
09/25/2014 09:18:24
I need it like this (yyyy-mm-dd):
2014-09-25 09:18:24
The object that this date goes into is a nullable date.
Tried this does not work:
DateTime formattedDate;
bool result = DateTime.TryParseExact(modifiedDate, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out formattedDate);
Any clues?
Thanks in advance.
From DateTime.TryParseExact
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 case, they are not. Use yyyy-MM-dd HH:mm:ss format instead.
string s = "2014-09-25 09:18:24";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
It is a little bit unclear but if your string is 09/25/2014 09:18:24, then you can use MM/dd/yyyy HH:mm:ss format instead. Just a tip, "/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. That means, if your CurrentCulture or supplied culture's DateSeparator is not /, your parsing operation will fail even if your format and string matches exactly.
If you have already a DateTime and you want to format it, you can use DateTime.ToString(string) method like;
dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25
or
dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24
Remember, a DateTime does not have any implicit format. It just contains date and time values. String representations of them have formats.
In answer to your question, to convert it as you prefer, do it like this:
string originalDate = "09/25/2014 09:18:24";
DateTime formattedDate;
if (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate))
{
string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
And then output will have your desired format.
DateTime dateOf = Convert.ToDateTime("09/25/2014 09:18:24");
string myFormat = "yyyy-mm-dd";
string myDate = dateOf.ToString(myFormat); // output 2014-18-25
Datetime format
I have string having value "August-25-2011". How can I parse that into Datetime format?
Try:
DateTime dt = DateTime.ParseExact(
your_date,
"MMMM-dd-yyyy" ,
CultureInfo.InvariantCulture);
Try this out.
var date = DateTime.Parse("August-25-2011");
DateTime.ParseExact(
your_date,
"MMMM-dd-yyyy" ,
CultureInfo.InvariantCulture);
For TryParseExact
DateTime parsedDate;
string pattern = "MMMM-dd-yyyy" ;
DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate)
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified array of formats,
culture-specific format information, and style. The format of the
string representation must match at least one of the specified formats
exactly. The method returns a value that indicates whether the
conversion succeeded.