I have a DateTime object with value as 2011-08-11T01:03:29+00:00 which is returned from a database.
How can I convert this to mm/dd/yyyy format where as the end result type should be DateTime object only, not string?
A DateTime object is only the numerical representation of the date as 'ticks' from a constant start time (for example, January 1, 0000). It is not the string representation. To get a string representation, you do ToString() on the object.
To convert your DateTime to a string for your custom format, use
myDateTime.ToString("MM/dd/yyyy");
See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx for complete details about DateTime.ToString() custom formats.
See http://msdn.microsoft.com/en-us/library/system.datetime.aspx:
"Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file."
Pass it as a string and parse it
format = "mm/dd/yyyy";
try {
result = DateTime.ParseExact(yourDate.ToString(format), format, provider);
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
MSDN has all answers
DateTime has functions called ToLongDateString() and ToShortDateString() (I believe those are correct function names) and the to short one does what you want.
Related
I'm using Google.Cloud.BigQuery.V2 to access big query. In my table I have a field created_at which is in Timestamp(ex: 2019-08-11 11:22:22.123 UTC). When I tried to convert this field into C# datetime it gives the following output:
8/11/2019 11:22:22 PM
And when I tried to convert this into a datetime (format : yyyy-MM-dd HH:mm:ss.fffffff) it gives me the following value
2019-08-11 22:22:22.0000000
But I want my output to look like this 2019-08-11 11:22:22.1230000
Here is my code
string created_at = $"{row["created_at"]}".ToString() == null ? "" : $"{row["created_at"]}".ToString();
DateTime date = DateTime.ParseExact(created_at, "M/d/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
string newDate = date.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
Console.WriteLine (newDate);
What am I doing wrong here? How to get milliseconds?
Use
var date=(DateTime?)row["created_at"];
var text=string.Format("{0:yyyy-MM-dd hh:mm:ss.fffffff tt}", date,
CultureInfo.InvariantCulture);
or
var date=(DateTime?)row["created_at"];
var text=FormattableString.Invariant($"{date:yyyy-MM-dd hh:mm:ss.fffffff tt}");
To read a BigQueryDbType.Timestamp value and format it into a string using a 12-hour notation and AM/PM designator in English.
Explanation
The source code itself shows that calling row["created_at"] converts a BigQueryDbType.Timestamp type gets converted to a UTC DateTime. This means that this code will work :
var date=(DateTime?)row["created_at"];
The returned date contains all the information there is. If the value contains milliseconds, date will also contain milliseconds. The source code shows that the value's precision is 10 microseconds.
DateTime is a binary value, it has no format. Formats apply only when a string needs to be parsed into a DateTime value or when a DateTime value needs to be formatted as a string for display or saving to a text file, with ToString(), String.Format() or string interpolation.
For example, the o standard format specifier creates a string in the ISO8601 format :
var date=DateTime.UtcNow.ToString("o")
//2019-09-18T14:02:22.2048166Z
HH is the double digit specifier that returns a 24-hour value (0-23) while hh returns the hour between 0 and 12. When hh is used the t (AM/PM designator) should also be used, otherwise there's no way to say whether the hour is 10 AM or 10 PM.
This return 14:00 etc :
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff")
//2019-09-18 14:07:48.2517651
While this returns
DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss.fffffff")
//2019-09-18 02:08:45.1001800
Which is a problem - is this AM or PM? Adding tt at the end fixes this, but the returned designator would be localized. To ensure a specific designator is used, we need to pass a CultureInfo parameter :
DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss.fffffff tt",CultureInfo.InvariantCulture)
//2019-09-18 02:10:39.9194735 PM
Putting it all together, to get the date from BigQuery and then format it as a string using AM/PM :
var date=(DateTime?)row["created_at"];
var text=string.Format("{0:yyyy-MM-dd hh:mm:ss.fffffff tt}",date,CultureInfo.InvariantCulture);
The equivalent using string interpolation would be :
var text=FormattableString.Invariant($"{date:yyyy-MM-dd hh:mm:ss.fffffff tt}");
You should use this
string newDate = date.ToString("yyyy-MM-dd hh:mm:ss.fffffff");
More on Format specifiers here
I saw a lot of change date time format, but all change the string to date time and change date time into the string format.
My problem is I failed to convert the date time format (5/1/2020 12:00:00 AM) into date time format (2020/05/01 00:00:00) not string.
My value and text for date time that I saw in Watch
dueDatePicker.Value = {5/1/2020 12:00:00 AM} type is system.DateTime
dueDatePicker.Text = "Friday, May 01, 2020" type is string
and I tried a lot of methods and I also confuse now. My last method is
DateTime calibrateDate = DateTime.ParseExact(Convert.ToString(dueDatePicker.Value), "yyyy-MM-dd HH:mm", null);
And I get an error:
System.FormatException: 'String was not recognized as a valid DateTime.'
I need your help to convert the value into date time format (yyyy-MM-dd HH:mm:ss)
You don't need to convert a date to a string just to parse it back into a date. Just grab the date directly:
DateTime calibrateDate = dueDatePicker.Value;
If you want to display that date as a string, then convert it using ToString:
string calibrateDateAsString = calibrateDate.ToString("yyyy-MM-dd HH:mm");
What you are doing is how you convert a string to date, but you already have a date type, why are you converting it back to a string and then formatting the string to a date again?
You can just simply do this:
dueDatePicker.Value.ToString("yyyy-MM-dd HH:mm")
I've got the following String format: "26/10/2017 22:54:22"
im trying to convert it to DateTime object, which should be of the same format as the string (24hours format) but somewhy it generates a 12h format.
my code:
var time = "26/10/2017 22:54:22";
DateTime convertedDate = DateTime.ParseExact(time, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(convertedDate);
Console.ReadLine();
the output i get is: 10/26/2017 10:54:22 PM
any ideas why is that?
DateTime by itself doesn't make any difference if the time is 12-hour or 24-hour, it's only when converted to a string that there is a difference.
Console.WriteLine will call the ToString() method (the one without any parameters) of the object passed as parameter. For a DateTime, ToString() formats the date and time according to the current locale. Yours is probably set to a 12-hour format.
If you need to print your time with a different format, you should format the DateTime explicitely, using another variant of the ToString method.
In your case:
Console.WriteLine(convertedDate.ToString("MM/dd/yyyy HH:mm:ss"));
If you have successfully parsed into a DateTime structure, there is overloaded method of ToString for DateTime, which is converts the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture.
So in your case you can just use:
Console.WriteLine(convertedDate.ToString("MM/dd/yyyy HH:mm:ss"));
MSDN Link: DateTime.ToString Method (String)
I'm using a library called Json.NET that uses the following code internally to parse a JSON string into a DateTime:
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt);
return dt;
}
I thought Json.NET was screwing up the conversion, but it looks like it's DateTime.TryParse itself that's botching the value.
When I parse the following valid Iso date (which corresponds to UTC DateTime.MinValue):
string json = "0001-01-01T00:00:00+00:00";
DateTime dt;
DateTime.TryParse(json, invariantCulture, DateTimeStyles.RoundtripKind, out dt);
The result is a localized DateTime: {0001-01-01 8:00:00 PM}, which when converted back to Utc time gives {0001-01-02 0:00:00 PM}. Essentially, the date underflowed, which is exactly the kind of problem you would expect DateTimeStyles.RoundtripKind to avoid.
How do I avoid this scenario?
Why use DateTimeStyles.RoundtripKind? The documentation for RoundtripKind says:
The DateTimeKind field of a date is preserved when a DateTime object is converted to a string using the "o" or "r" standard format specifier, and the string is then converted back to a DateTime object.
The string output from the "o" or "r" standard format specifiers are not like the ISO 8601 string you are trying to parse. It doesn't sound to me like RoundtripKind is really supposed to work with any date time string format. It sounds like the round trip is for the DateTime.Kind property when the string is in a particular format.
Since you know the format of the string you are trying to parse, then I would suggest using DateTime.TryParseExact.
I have had to support a couple different versions of the ISO 8601 string - either of these formats are valid date-time values in ISO 8601 (and there are even more options for dates, times and fractional seconds, but I didn't those):
0001-01-01T00:00:00+00:00
0001-01-01T00:00:00Z
Here's a method that will handle either of these formats:
private bool TryParseIso8601(string s, out DateTime result)
{
if (!string.IsNullOrEmpty(s))
{
string format = s.EndsWith("Z") ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:sszzz";
return DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result);
}
result = new DateTime(0L, DateTimeKind.Utc);
return false;
}
I have a excel sheet in which am taking a date column in this format "23/8/11 01:33:01:PM"
and am inserting it in sql 2008 using datarow but am getting a error
String was not recognised as valid datetime.
Can any one please help?
DateTime newdate = Convert.ToDateTime(row[8].ToString());
Here how Convert.ToDateTime method looks like when you decompile it;
public static DateTime ToDateTime(string value)
{
if (value == null)
return new DateTime(0L);
else
return DateTime.Parse(value, (IFormatProvider) CultureInfo.CurrentCulture);
}
As you can see, this method use DateTime.Parse method with your CurrentCulture. And if your string doesn't match your current culture date format, your code will be broken. That's the reason you get this error.
Use DateTime.ParseExact with "dd/M/yy hh:mm:ss:tt" format instead.
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 or an exception is thrown.
string s = "23/8/11 01:33:01:PM";
DateTime newdate = DateTime.ParseExact(s, "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
Console.WriteLine(newdate);
Output will be;
8/23/2011 1:33:01 PM
Here a DEMO.
For your case;
DateTime newdate = DateTime.ParseExact(row[8].ToString(), "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
For more informations, take a look;
Custom Date and Time Format Strings
Convert.ToDateTime internally calls DateTime.Parse which by default will use the current culture of your application. If 23/8/11 01:33:01:PM is not a valid format for this culture then this method will fail.
For specific date formats it's best to use DateTime.ParseExact e.g.
DateTime.ParseExact("23/8/11 01:33:01:PM", "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
This approach makes your code culture independent which means the date will always be parsed correctly (given it's in the specified format).
This will work:
DateTime newdate = Convert.ToDateTime("8/23/11 01:33:01 PM");
I changed day and month and removed the colon a the end. But that is very specific. You need to know more about the dates passed to do that.