Can't convert time to ISO 8601 using C# - c#

Consider this code:
TimeStamp.Text = BlogComment.Date.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");
BlogComment.Date is a DateTime object with its date set. TimeStamp is just a literal.
I keep getting unrecognised escape sequence. How can I fix this problem?

You want a string literal - prefixing a string with # will not parse the string for escape sequences like you have in your string but take it in "literal" form.
#"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz"
Edit:
Also there is no UtNow property on DateTime - this is a static property only available on the DateTime class. You can just write:
TimeStamp.Text = BlogComment.Date.ToString(#"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");
or if your intention was to convert the time to UTC:
TimeStamp.Text = BlogComment.Date
.ToUniversalTime()
.ToString(#"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");

EDIT:
TimeStamp.Text = BlogComment.Date.ToUniversalTime().ToString(#"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");

Try this:
Stamp.Text = BlogComment.Date.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");
Or
Stamp.Text = BlogComment.Date.ToString(#"yyyy-MM-ddTHH:mm:ss.fffffffzzz");
My mistake: The \ is indeed required, because it might be a custom format specifier.
And if you just want the current time, use
Stamp.Text = DateTime.UtcNow.ToString(#"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");
UtcNow is static. It should not be accessed from an instance. It should be accessed from the class itself.
Alternatively, you might want:
Stamp.Text = BlogComment.Date.ToUniversalTime().ToString(#"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");
This would get you the universal time of the Date in BlogComment.

When dealing with escaping characters in a DateTime format string, there's a similar question where #Oppositional's writes
When using custom format strings with
a DateTime, it is important to remeber
that you need to escape your
seperators using single quotes.
string time = DateTime.UtcNow.ToString(
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz",
DateTimeFormatInfo.InvariantInfo);
The characters surrounded by the single quotes ' are literal strings inside a DateTime format string.
However, escaping the - and : is redundant if you are also specifying the Invariant culture. You should always specify the culture when formatting dates and times.
It's also important to note that / and : are the (invariant) date and time separators in a DateTime format string. DateTime.ToString will use the current cultures to transform them as necessary. For example, Italian (it-IT) has the . as its time separator. Similarly fr-CH has a date separator of .
You can see this escaping in action if you take a look at System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.UniversalSortableDateTimePattern which is yyyy'-'MM'-'dd HH':'mm':'ss'Z'

DateTime.UtcNow..ToString("o");
(o) Roundtrip (local):. . . . 2006-04-17T14:22:48.2698750-07:00
(o) Roundtrip (UTC):. . . . . 2006-04-17T21:22:48.2698750Z
(o) Roundtrip (Unspecified):. 2000-03-20T13:02:03.0000000
http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.85).aspx

Related

Utcoffset formats in C#

var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Console.WriteLine(((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));
The above code is working fine. But I need to display offset like +05:00. Is there any way to achieve this format?
From the docs:
The custom TimeSpan format specifiers don't include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals.
So you have to escape character in your format string that is not listed in the above page, either by surrounding it with ', or with a backslash, so:
utcOffset.ToString("hh':'mm")
However, you don't actually have to do this formatting yourself, if you format a DateTimeOffset, rather than TimeSpan. If you do this, you don't need all the "getting the UTC offset" mess either.
You just need the zzz Custom Format Specifier:
DateTimeOffset.Now.ToString("zzz")
You don't need all of the TimeZone stuff.
Instead of using TimeZone to look up the timezone from DateTime.Now, you can use DateTimeOffset.Now with the zzz format string and CultureInfo.InvariantCulture to achieve this:
Console.WriteLine(DateTimeOffset.Now.ToString("HHmmzzz", System.Globalization.CultureInfo.InvariantCulture));
// outputs 1255+02:00
Try it online
If you just want the offset in that format, you can use "zzz" instead of "HHmmzzzz".

format timestamp as string in c#

I have a Timespan variable which should store the resulting subtraction operation from two datetime value and then display them in a dd:hh:mm format.
This is what I have tried so far and it doesn't work
Duration=(DateTime.Now- instance.StagesInformations.Last().Value.TransactionDate).ToString("\\hh:mm")
Please help
TimeSpan formatting strings are somewhat different than DateTime formatting strings. You need to escape literal characters like ::
.ToString("dd\\:hh\\:mm")
or use # so you don't have to escape the formatting escape characters:
.ToString(#"dd\:hh\:mm")
That said, why not just store as a TimeSpan and let the display layer format it? (I'm assuming you're storing in a class property based on your syntax)
To achieve your desired format dd:hh:mm it should be .ToString(#"dd\:hh\:mm")
See MSDN for reference.

Discard functionality of "/" in CultureInfo

What property in CultureInfo.InvariantCulture helps to discard the functionality of "/".
I am having this problem because I have my customCulture.
and when I use it to format DateTime it replaces "/" with the culture Specific separator.
So I want to know what property if I change in my customCulture the functionality of "/" will be discarded.
Let me clear my problem,
I want to export some data to a file with DateTime as specified by user.
I am creating customCulture as follows
CultureInfo customCulture = new CultureInfo(CultureInfo.CurrentCulture.Name);
I am taking the date format from the user and injecting it into my CustomCulture object as
customCulture.DateTimeFormat.ShortDatePattern = MyClass.DateFormatFromUser;
Now when I want to convert this to String pattern. I am doing it as follows,
string.Format(customCulture, "{0:G}", dateTimeValue);
Now the problem is String.Format replaces any "/" present in ShortDatePattern with customCulture.DateTimeFormat.DateSeparator
For example if he user gives the format as
dd/MM/yyyy
and my current culture is faeroese ie., {fo-FO}
For these I get output as 25-09-1990.
If you want to change your custom culture so that the date separator is the slash (/) then you are looking for the DateTimeFormatInfo.DateSeparator property:
customCulture.DateTimeFormat.DateSeparator = "/";
Use the escape character \: change every / into \/ when you don't want it to be replaced with culture separator.
DateTimeFormatInfo.DateSeparator is the culture-specific separator that separates the components of a date.
What you ask is not possible and Marcin Juraszek is right. There is a misunderstanding of how the format specifier and the CultureInfo work together.
The / character is a format specifier just like m,D,y,Y and all the other date format specifiers. That's just the syntax of the format string, it has nothing to do with culture and can't change. You can't change the meaning of '/' any more than you can change the meaning of the other specifiers
String.Format uses this specifier to find where it should place the CultureInfo's DateSeparator character when formatting a date.
It doesn't matter whether you include the specifier directly in a format string like String.Format("{0:dd/MM/yyyy}",DateTime.Now) or you pass it indirectly through CultureInfo.DateTimeFormat.ShortDatePattern like you tried, it will always be replaced by the DateSeparator character.
Your only option is to escape the character either by prepending it with '\' or surrounding it with ' ' as cremor suggested, eg.
customCulture.DateTimeFormat.ShortDatePattern = "dd\\/MM/yyyy";
or
customCulture.DateTimeFormat.ShortDatePattern = "dd'/'MM/yyyy";
So, if you wanted to create a string like 11-07/2013 you would have to write something like this:
CultureInfo customCulture = new CultureInfo(CultureInfo.CurrentCulture.Name);
customCulture.DateTimeFormat.ShortDatePattern = "dd/MM\\/yyyy";
customCulture.DateTimeFormat.DateSeparator = "-";
var dateTimeValue = DateTime.Now;
var result = string.Format(customCulture,"{0:d}", dateTimeValue);
Console.WriteLine(result);

DateTime ToString(“dd/MM/yyyy”) returns dd.MM.yyyy

I have also tried shielding the '/' symbol in the formatting string, but it didn't quite work. My final goal is to get the date with the '/' symbols as separators. I guess I can use DateTime.ToString(“dd/MM/yyyy”).Replace('.', '/'), but that feels a bit excessive.
The / character in date/time format strings stands for "whatever the date separator of the format provider is". Since you do not supply a format provider Thread.CurrentCulture is used, and in your case the current culture uses . as the date separator.
If you want to use a literal slash, place it inside single quotes:
dateTime.ToString("dd'/'MM'/'yyyy");
Alternatively, you could specify a format provider where the date separator is /:
dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
All of the above is documented on MSDN.
See the difference in a live example.
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
This is because of the way ToString works by default, in accordance with the current culture:
This method uses formatting information derived from the current
culture.
So, override that:
string date = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
This works (note the InvariantCulture):
DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
If a CultureInfo is not specified, the CurrentCulture will be used. If this is a culture that doesn't use slashes as separators in dates it is replaced by whatever the actual culture date separator is.

DateTime.ParseExact string format exception

I am trying to convert a string into datetime with the following C# code,
DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);
eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.
What string format should I use to support both 01/01/2010 and 1/1/2010?
Using the following date format expression will allow you to use either single or double digit day and month elements.
"M/d/yyyy"
Note that the capital M is significant - a lower case m is the placeholder for minutes.
You will find more information related to date format strings here.
You can use the following Powershell command to test them.
[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)
Capital M is month, little m is mins i think.
But to the point of the question, use Parse. ParseExact implies you know the exact format of the input.
You could try this format: MM/dd/yyyy, but I think there's no single format string that could support both inputs. You could test if the length of your dateTo string is less than 10 characters use M/d/yyyy, otherwise MM/dd/yyyy.

Categories