Setting a dateTime with only two characters as milliseconds - c#

I have a WCF webservice I use to set some date using the following code :
foo.StartDateTime = DateTime.UtcNow;
Unfortunately, at the output of the WCF webservice, the date is the following :
<a:startDateTime>2019-01-30T08:54:13.698Z</a:startDateTime>
The issue is that the millisecond part must be on 2 characters only because our middleware can process only date like that. I know it's valid ISO 8601 but still.
How is it possible to set the date that will be in the response of the WS with only two characters ?

Related

How do I convert this date in to a valid date object?

I am trying to convert string dates like 2020-01-14T17:01:48.757Z and 2020-01-14T17:01:50.760Z in to C# DateTime. Looks like my parsing is failing somewhere.
DateTimeOffset.ParseExact("2020-01-14T17:01:48.757Z", "yyyy-MM-dd'T'HH:mm:sszzz", CultureInfo.InvariantCulture).DateTime;
Whats wrong with above code ? It fails with
String '2020-01-14T17:01:50.760Z' was not recognized as a valid
DateTime.
When I parse same date online https://nsdateformatter.com/ It has no issues.
I even tried using yyyy-MM-dd'T'HH:mm:ssZ but it also gives above error.
Use this date format:
DateTimeOffset.ParseExact("2020-01-14T17:01:48.757Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture).DateTime;
2020-01-14T17:01:48.757Z
yyyy-MM-ddTHH:mm:ss.fffZ
As You see format corresponds to Your provided date string.
Looks like you forget to use proper format specifier for your milliseconds part and dot (.) between your seconds and milliseconds part.
The "fff" custom format specifier
The "fff" custom format specifier represents the three most
significant digits of the seconds fraction; that is, it represents the
milliseconds in a date and time value.
DateTimeOffset.ParseExact("2020-01-14T17:01:48.757Z",
"yyyy-MM-dd'T'HH:mm:ss.fffZ",
CultureInfo.InvariantCulture)

AspNet Core - Specify the DateTime Format

I am consuming a third party API which expects an HTTP header value as below (using the format below).
Date: 2017-10-15T14:25:21Z
When I try to add the header as below, I am getting invalid date time format error (when the client inject the header during runtime)
client.DefaultRequestHeaders.Add("Date", "2017-10-15T14:25:21Z");
So I change the code above to as below
client.DefaultRequestHeaders.Date = DateTime.UtcNow;
However, the API throws back an exception "Hmac timestamp 2019-01-02 is not a valid ISO8601 dateTime"
How do I pass the expected date time format in the HTTP request header?
EDIT
-
I know how to get a date string in a specified format. What I am asking here is how do I pass a UTC date object to HTTP header as below with a specific format. I also realise that datetime object cant have a format in it.
**client.DefaultRequestHeaders.Date = DateTime.UtcNow**
Do that like this
DateTime dt=Convert.ToDateTime("2019-01-02");
string yourdate = dt.ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(yourdate);
Working example

C# DateTimeInvalidLocalFormat - How to set timezone to UTC

I'm working in a EasyPost integration making a class library to make the use of their API simpler and I'm getting this error:
Managed Debugging Assistant 'DateTimeInvalidLocalFormat' has detected a problem in 'C:\Projects\TestClient.vshost.exe'.
Additional information: A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output. In that case, either use the 'Z' format specifier, which designates a UTC time, or use the 'o' format string, which is the recommended way to persist a DateTime in text. This can also occur when passing a DateTime to be serialized by XmlConvert or DataSet. If using XmlConvert.ToString, pass in XmlDateTimeSerializationMode.RoundtripKind to serialize correctly. If using DataSet, set the DateTimeMode on the DataColumn object to DataSetDateTime.Utc.
I get this error when I call the Create method in the EasyPost Shipment object. Code below:
Shipment shipment = new Shipment() {
to_address = toAddress,
from_address = fromAddress,
parcel = parcel
};
shipment.Create();
This create function probably makes a call to their REST API and is trying to convert a json response into one of their models.
To solve the error I'm trying to set the UTC as the default of my library so whenever I use DateTime.ToString() I use the DateTime.ToString("o"). I don't know if this would actually solve the problem, but I don't know how to force it (use UTC as the library default). I have tried the piece of code below, but it doesn't work
CultureInfo newCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = newCulture;
Can you help me?
I'm one of the developers on the EasyPost client libraries.
As far as I can find in some basic research, there's no (easy) way to set a default time zone for a C# application. Most of the blog posts and other SO answers I found suggest using utility functions to convert a UTC datetime object to a local datetime object when trying to display it to a string.
EasyPost's API returns all datetimes in UTC time + timezone information (ex. 2022-10-24T12:37:24-06:00), which is accounted for when the JSON is deserialized into a DateTime object in the C# client library.

Webtest - Using Dates as Context Parameters

I've created a webtest and have a CSV data source that contains a column with a list of short dates (MM/dd/yyyy)
I need to manipulate the parameter due to part of the web page I'm testing has a form parameter that needs it to be formatted as yyyyMMdd
When the date that is captured from the data source (ex: 02/12/2016), I noticed in the Context tab of my test run that the format to "2/12/2016 12:00:00 AM"
I've created a Request plug-in and added the following code:
public override void PreRequest(object sender, PreRequestEventArgs e)
{
base.PreRequest(sender e)
string CSVDate = e.WebTest.Context["<datasource date column>"].ToString();
DateTime dt = DateTime.ParseExact(CSVDate, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
e.WebTest.Context.Add("NewDate", dt.ToString("yyyyMMdd"));
}
This generates a String was not recognized as a valid DateTime error. I tried changing the format to MM/dd/yyyy, but I encountered the same error.
Does anyone know how the correct DateTime format I should be using?
The date-time as shown in the context is 2/12/2016 12:00:00 AM. This has only one digit for the month whereas the format specifier has MM which wants two digits. The date-time also contains the letters AM that are not matched by the format.
Modifying the format to be M/dd/yyyy HH:mm:ss matches the date-time 2/12/2016 12:00:00, but does not match the AM part. In theory the tt format specifier should match this, but it did not work for me.
Rather than using ParseExact you can use Parse and it works out the correct format. Using the following worked on the date-time string provided:
DateTime dt1 = DateTime.Parse(CSVDate, new System.Globalization.CultureInfo("en-US"));
The CultureInfo is needed because the input date has the month and the days the wrong way around.
However, the real problem is in the way CSV files are handled by the web test. It appears to read them using the same logic as Microsoft Excel uses when reading CSVs. Namely, if it looks like a date then convert it to a date. So any string matching dd/dd/dddd (where d is a digit) might be connverted to a date. (E.g. 15/15/2017 will not be converted because 15 is not a month number.) I recommend rewriting the CSV to format the input date differently, use something that Excel would not treat as a date. One option is to have the date in three columns of the CSV, so have explicit day,monthandyearcolumns. Another option is to add non-date characters to the string and format it correctly, eg asz20160212and then remove thezwithin the web test. Generally, I would advise to avoid the conversion of string toDateTime` then another conversion to a different string.

Accurate DateTime string format

I have a DateTime variable that holds the following value: 5/11/2014 7:56:26 am
I am currently using the following code to format this as a string: uDate.ToString("s"). Using this code, I get the following value: 2014-11-05T07:56:26
I need this to be more accurate. The exact value I am wanting to get is in the following range of accuracy: 2014-11-05T07:56:26.4
I have done some research at the following link: http://www.w3.org/TR/NOTE-datetime
Here is what I have found:
This profile does not specify how many digits may be used to represent
the decimal fraction of a second. An adopting standard that permits
fractions of a second must specify both the minimum number of digits
(a number greater than or equal to one) and the maximum number of
digits (the maximum may be stated to be "unlimited").
The value I am wanting to get is the value used on Azure when displaying a DateTime variable in a web service request.
How can I format my own DateTime strings so that they are the same format as the format used on Azure? Is there a specific format that Azure uses?
Basically, how can I format a DateTime string to be more accurate than the code: uDate.ToString("s")
Thanks in advance.
I believe the most "complete" information would be to use the "O" value, including fractions and also TimeZone (when available).
var myDate = DateTime.Now.ToString("o");
See also this article. Microsoft states that "complies with ISO 8601" and every .Net platform (also Azure) is able to read this string as DateTime, and also properly set the 'DateTimeKind' when available.
"s" standard format specifier uses SortableDateTimePattern property of your CurrentCulture and it doesn't includes miliseconds part.
This format specifier is always the same regardless the culture you use and it is "yyyy'-'MM'-'dd'T'HH':'mm':'ss" format.
You can just use custom date and time format strings like;
uDate.ToString("yyyy-MM-dd'T'HH:mm:ss.f");

Categories

Resources