format timestamp as string in c# - 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.

Related

DateTime format - one digit day not recognized

I need to read a String in the following format: "6102015" (meaning October 6th, 2015) and turn it into DateTime objects.
I tried the following code, which did not work:
DateTime.ParseExact("6102015", "dMyyyy", CultureInfo.CurrentCulture);
But when I tested the code using the date string with an extra 0, it worked.
DateTime.ParseExact("06102015", "dMyyyy", CultureInfo.CurrentCulture); // works correctly
Is there a way to read this date format without having to add the 0?
I thank you in advance for any help.
Is there a way to read this date format without having to add the 0?
Adding a 0 is the least of your worries, IMO. That takes one line of code.
Assuming you've got a copy of the database or something you can alter, effectively, I would:
Create a field of a date/time type, or if you must use a string, do so but use an ISO-8601 format (yyyy-MM-dd)
Parse all the values which are already 8 characters
Parse all the values which are 6 characters by inserting two 0s (so abcccc becomes 0a0bcccc)
For each remaining value, of the form abcyyyy:
Try parsing it as 0abcyyyy
Try parsing it as ab0cyyyy
If only one parse worked, store that result in the new column
Now look at all the remaining rows (i.e. the ones you haven't populated with a "known good" value
You may be able to use other data (such as insertion order) to work out which is the "right" parse...
You may not - in which case you need to decide what to do

Why does TimeSpan.ToString() require escaping separators?

You can specify a custom format for a DateTime object like this:
DateTime.Now.ToString("HH:mm:ss"); // 19:55:23
But when I try to use the same format for a TimeSpan object like this:
DateTime.Now.TimeOfDay.ToString("HH:mm:ss");
I get the "Input string was not in a correct format." exception.
It turns out, the solution is that you need to escape the ':' characters like in "HH\\:mm\\:ss". Note that there is a double backslash because if you specify only one, it will break the string so you need to escape that one too.
The question is, why .NET Framework developers made it this way? There must be a reason for sure. Why can't we use custom format specifiers without escaping them like we can with a DateTime object?
Looking for .NET gurus to shed light on this subject.
As stated in documentation, one of the differences between DateTime.ToString and TimeSpan.ToString format specifiers is the following: the custom TimeSpan format specifiers do not 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.
In contrast with TimeSpan (see table of format specifiers in docs), DateTime format specifiers include predefined symbols for Date separator /, and for Time separator :. It means that for example for Italian culture semicolon will be recognized as time separator (not the literal) and will be replaced with . symbol:
// outputs 09.57.18 instead of 09:57:18 because of Italian culture.
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss", CultureInfo.GetCultureInfo("it-IT")));
I think .NET designers made such difference between DateTime and TimeSpan string formatters intentionally, and it is quite reasonable. This is because historically Date/Time were formatted differently for different cultures. And .NET tried to provide globalization means for that matter along with DateTime type. But TimeSpan did not get such 'globalization' duties, it is just a type representing period of time, and formatting of it is not tied to any culture specifics (if they are ever existed), but instead formatting of it is constant in different culture settings.

Formatting String Variables that contain numbers/dates for printing in C#

Maybe it's a n00b question but I've looked at the .net/C# MSDN Library and on this site and have yet to come to a clear answer... say I had For Ex:
(this is not exactly the problem, as I'm not creating the string but reading them out of a DB. But serves to illustrate what I'm working with...)
string dob = "01/02/1990";
dob.ToString("MM/dd/YY"); //however, I can't do this. compiler gives me an error...
likely because it is already a string? How then could I get the string into the format that I want using specifiers, when it's already a string?
I know I could convert it to something else (a DateTime for Ex) and convert back to string using the ToString()...but this seems counter productive... to me at least
I also have several other "kinds" of string variables I'm trying to display into specific formats whilst saving them to a Idictionary for printing into a pdf's fields.
For ex:
d["amount"] = prod.sales.StringAmount; //(here StringSmount holds say 50000 (gotten from a DB), which I want to display as "50,000")
However, I also can't do prod.sales.StringAmount.ToString("N", CultureInfo.CurrentUICulture); cuz it's already a string! Is there an easy way to do this
or need I mess with String Buffers or the StringBuilder class??
thanks!
You can do something like this:
DateTime dob = DateTime.Parse("01/02/1990");
and then
dob.ToString("MM/dd/YY");
will work.
Note that DateTime.Parse() has various options for the possible date-time formats to accept, and that there is also a TryParse() version that returns false if the string is not a valid date - instead than throwing an exception. There are also DateTime.ParseExact() and DateTime.TryParseExact() variations.
Use the same approach for other data types beside date-times: first convert the input string in the correct data type (integer, float etc) - using the various Parse() or TryParse() methods, and then format the result of this conversion.
ToString returns a value without modifying the original.
Instead of
dob.ToString("MM/dd/YY");
use
dob = dob.ToString("MM/dd/YY");
First parse the string into a DateTime instance (via the Parse() or TryParse() methods). On the DateTime Instance you can then call ToString(..).
Using the format provided above, you would need to convert back to DateTime to use the .ToString("MM/dd/YY") format. The reason why is ToString is used to convert an object/value to a string representation and the DateTime object is nice enough to accept a format.
If you want to Format what is already a string, then you should be using String.Format. Visit this link: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx. This link shows the standard numeric formatters.
You may also want to create your own string format. Look into IFormatProvider and ICustomFormatter: http://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx.
I would recommend first parsing it into a number/DateTime and then using the string formatting variables. For an example of why this can be necessary, consider that your "01/02/1990" string is ambiguous between Jan 2 and Feb 1, unless you parse it using DateTime.ParseExact.
I'd recommend this over 'rolling your own' (e.g. with StringBuilder) so that you can use the built-in culture-sensitive string formatting abilities of .NET.

Can't convert time to ISO 8601 using 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

How do I keep the 0's in a Date

I am trying to figure out how it is that I can keep the 0's or add them when I grab a date.
What Im getting is this:
6/15/2010
What I'm tring to get is:
06/15/2010
I have added it so that it checks the length to and if its less than 6 (im stripping the "/") it pads the left side. That solves the issue when the month is a single digit, but what about when the date is a single digit.
My ultimate goal is to have a date such as:
1/1/2010
read out like:
01/01/2010
Any suggestions would be greatly appreciated.
Use a custom format : dd/MM/yyyy, or in your case MM/dd/yyyy. Note the capital M, the small m gets you the minutes.
string s = DateTime.Now.ToString("MM/dd/yyyy");
You need to use a custom DateTime format string:
string str = someDate.ToString("dd/MM/yyyy");
It depends on the format of date you are using.
For instance, dd/MM/yyyy will produce 01/05/2009 and d/M/yyyy would produce 1/5/2009
A complete reference can be found there : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You want something like this:
string myDate = "1/1/2010";
DateTime date = DateTime.Parse(myDate);
string formattedDate = date.ToString("MM/dd/yyyy");
If the starting date is some other unrecognized format you could use DateTime.ParseExact();
Use DateTime.ParseExact() to parse the string into a valid datetime object and then use DateTime.ToString("dd/MM/yyyy") to get result in desired format.

Categories