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
Related
I have this code, it gives day's value as 1,2,3 .. instead of 01,02,03..
(DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture))
gives: 4/16/2016 12:00:00 AM.
I need 04/16/2016 12:00:00 AM
I have tried different cultures but nothing worked.
DateTime doesn't store any formatting information, it's just a structure representing a date and time. ParseExact is parsing your date string correctly.
If you want it formatted, you supply a format to DateTime.ToString, for example:
var formattedDate = dateTime.ToString("MM/dd/yyyy hh:mm:ss tt");
See this fiddle.
DateTime.ParseExact returns DateTime which doesn't have any implicit format. This "format" concept only applies when you get it's textual (a.k.a. string) representation.
You didn't told use how and where you see this 4/16/2016 12:00:00 AM string but if you wanna get days part with leading zero, you can use The dd format specifier with a proper culture (for calendar and time designators).
The dd custom format string represents the day of the month as a
number from 01 through 31. A single-digit day is formatted with a
leading zero.
DateTime dt = DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture);
string str = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// 04/16/2016 12:00:00 AM
I am receiving a JSON DateTime from a web service in the following format
yyyy-MM-ddTHH:mm:ss zzz
For example:
2016-04-18T15:09:21 01:00
However, I am unable to convert this into a DateTime object. I have tried the following:
var date = DateTime.ParseExact("2016-04-18T15:09:21 01:00", "yyyy-MM-ddTHH:mm:ss zzz", CultureInfo.InvariantCulture);
var date2 = DateTimeOffset.ParseExact("2016-04-18T15:09:21 01:00", "yyyy-MM-ddTHH:mm:ss zzz", CultureInfo.InvariantCulture);
Both of these lines throw the System.FormatException exception with the message:
String was not recognized as a valid DateTime.
How can I parse 2016-04-18T15:09:21 01:00 as a DateTime object?
Unfortunately the "zzz" expects a sign on the timezone.
This will work.
var date = DateTime.ParseExact("2016-04-18T15:09:21 +01:00", "yyyy-MM-ddTHH:mm:ss zzz",System.Globalization.CultureInfo.InvariantCulture);
date.Dump();
So add a plus sign.
var dt="2016-04-18T15:09:21 01:00";
dt.Insert(20,"+").Dump();
Dmitriy has the right answer, from The "zzz" custom format specifier documentation;
The offset is always displayed with a leading sign. A plus sign (+)
indicates hours ahead of UTC, and a minus sign (-) indicates hours
behind UTC. A single-digit offset is formatted with a leading zero.
If your string is always in yyyy-MM-ddTHH:mm:ss HH:mm format, you have to manipulate it if you wanna parse it to DateTimeOffset.
I would suggest to you split your string with a white space, call DateTime.Parse and TimeSpan.Parse on those strings and use those values in a DateTimeOffset(DateTime, TimeSpan) constructor which;
Initializes a new instance of the DateTimeOffset structure using the
specified DateTime value and offset.
var str = "2016-04-18T15:09:21 01:00";
var parts = str.Split(' ');
var date = DateTime.Parse(parts[0]);
var offset = TimeSpan.Parse(parts[1]);
var dto = new DateTimeOffset(date, offset);
Now you have a DateTimeOffset as {18.04.2016 15:09:21 +01:00} and you can use it's DateTime, LocalDateTime or UtcDateTime properties whichever you want.
I have one object {System.DateTime} value is {5/17/2010 12:00:00 AM}.
I want to convert this datetime format to "d-MMM-yyyy",
string msStartDt="5/17/2010 12:00:00 AM";
DateTime.ParseExact(msStartDt, "MM/dd/yyyy HH:mm:ss",CultureInfo.InvariantCulture).ToString("d-MMM-yyyy");
String was not recognized as a valid DateTime.
second parameter of ParseExac() method is a format specifier that defines the required format of msSartDt.
If I change {5/17/2010 12:00:00 AM} to {17-Dec-2010 12:00:00 AM} we need to change 2nd parameter of DateTime.ParseExact()
My question is how we can find programatically the format of msStartDt so we can put in second parameter of DateTime.ParseExact() method.
You need to use
M specifier instead of MM specifier since single digit numbers don't have leading zero
hh specifier instead of HH specifier since you are using 12-hour format
tt specifier for AM/PM designators
string msStartDt = "5/17/2010 12:00:00 AM";
var str = DateTime.ParseExact(msStartDt, "M/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture).ToString("d-MMM-yyyy");
On the other hand, your question is vauge. You said I have one object DateTime value is 5/17/2010 12:00:00 AM but you have a string in your code as it.
If you have already a DateTime, you just need to format it with ToString method. You don't need parsing at all.
DateTime dt = ...
var str = dt.ToString("d-MMM-yyyy", CultureInfo.InvariantCulture);
My question is how we can find programatically the format of msStartDt
so we can put in second parameter of DateTime.ParseExact() method.
It is not possible.
Think about you have a string like 01/02/2015. What is the proper format of this string? It is 1st February or 2nd January? Is it dd/MM/yyyy or MM/dd/yyyy? It is totally ambiguous as you can see. If you have a string formatted, you have to know it's proper format to parse a DateTime.
You need to specify AM/PM in your string format:
DateTime.ParseExact(msStartDt, "M/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture)
also you need to change from HH to hh because HH is for 24h dates
Here you have all datetime fromat constants.
Please try this one:
DateTime.ParseExact(msStartDt, "M/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture);
When we use the ParseExact the format of the string we parse must be exactly the same with the string. In your case you had omitted the AM/PM designator. Furthermore you need to correct the months and hours. For futher information, please have a look here.
You should specify the correct parse format
DateTime.ParseExact(msStartDt, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture).ToString("d-MMM-yyyy")
Firstly, convert your specified date from String to DateTime, then convert to another date format:
string dateString;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "05/17/2010 12:00:00 AM";
DateTime dt = Convert.ToDateTime(dateString, provider);
Console.WriteLine(dt.ToString("d-MMM-yyyy HH:mm:ss tt"));
See other date time formats in the following link: http://www.csharp-examples.net/string-format-datetime/
Your output should be like the follow screenshot:
I have a varchar(5) column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration.
For Example
8:18 should be converted into 8:18:00 AM and then should be embedded
with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime
column of DB.
22:20......10:20:00 PM.......8/10/2012 10:20:00 PM
The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012
You can do something like this:
string input = "22:45";
var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);
string timeIn12HourFormatForDisplay = timeFromInput.ToString(
"hh:mm:ss tt",
CultureInfo.InvariantCulture);
var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);
And now the important parts to take in consideration:
The format for parsing uses "H:m" so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;
The format for printing uses "hh:mm:ss tt" because it seems to be the format you desire, however you need to use CultureInfo.InvariantCulture to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;
The full date and time is constructed based on DateTime.Today which returns the today date with a zeroed time and then we just add the time we read from input.
To create the final date and time from another date you can instead use:
var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);
Reference material:
DateTime Structure;
Custom Date and Time Format Strings;
Standard DateTime Format Strings.
create function dbo.COMBINE_DATE_TIME(
#DatePart DateTime, -- DateTime
#TimePart varchar(5)) -- Time
returns DateTime
as begin
return DATEADD(day, DATEDIFF(day,0,#DatePart),
CONVERT(DateTime,ISNULL(#TimePart,''),14))
end
go
string strDate = DateTime.ParseExact("8:18","HHmm",CultureInfo.CurrentCulture).ToString("hh:mm tt");
string fromTime = Convert.ToStr(reader["TimeFrom"]);
string toTime = Convert.ToStr(reader["TimeTo"]);
item.Time=DateTime.Parse(fromTime,CultureInfo.CurrentCulture).ToString("hh:mm tt");
here the property of your model(item.Time here) should be the string.
I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.
It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.
How can I do this for different culture ?
My datestring will always be in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.
Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.
string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(dateToConvert, format, provider);
Output:
{1999-08-01 00:00:00}
You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:
DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
Read more at:
Parsing Date and Time Strings
Standard Date and Time Format Strings
Custom Date and Time Format Strings
I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:
DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)
I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)
That's a very long-winded way to do it. Simply this will work:
DateTime.Parse("08/1999")
How can I do this for different culture ?
If your string is always in this format, do this:
DateTime.Parse("08/1999", CultureInfo.InvariantCulture)