c# Time formatting - c#

I have a time field as such: 06:30 PM.
What formatting do I need so that it shows up as 6:30 PM.
I tried:
String.Format("{0:t}", data.PgTime)
but still getting 06:30 PM

Well, t is the standard format string for "short time pattern" - so it's being formatted according to the current culture's rules. For me, it would show "18:30" because that's the appropriate format for the UK.
You can either stick to the rules .NET knows about, or you can use a custom date and time format string to force a specific format, e.g.
string text = date.ToString("h:mm tt");
(Note that this is basically equivalent to string.Format("{0:h:mm tt}", date) but considerably simpler to read - I'd suggest only using composite formatting when you're really formatting more than one value.)
Usually that would not be a good idea though - it suggests that you know more about cultural rules than Windows / .NET, which is unlikely to really be the case. I'm sure you know more about how you personally like to format dates and times, but that's not the same as it being the standardized convention for your culture.

String.Format("{0:h:mm tt}", data.PgTime)
See also:
Custom Date and Time Format Strings on MSDN.

Related

DateTime being weird

How come
w.WriteLine(Program.RegisterList[i].DateTime);
Writes : 11/20/2013 01:46:31 PM
But
w.WriteLine(Convert.ToDateTime(Program.RegisterList[i].DateTime, CultureInfo.InvariantCulture).ToString());
Writes 20/11/2013 1:46:31 PM
? Isn't invariant culture supposed to make it MM/DD/YY? I would like to use the invariant culture method incase a date slips by in DD/MM/YY format.
Thanks!
Edit: I should mention Program.RegisterList[i].DateTime is a string.
Edit2:
MessageBox.Show("11/20/2013 01:46:31 PM");
MessageBox.Show(Convert.ToDateTime("11/20/2013 01:46:31 PM", CultureInfo.InvariantCulture).ToString());
w.WriteLine(Convert.ToDateTime(Program.RegisterList[i].DateTime, CultureInfo.InvariantCulture).ToString());
You confused yourself by writing code you can't understand anymore. A simple rewrite of that one honking statement:
string s = Program.RegisterList[i].DateTime;
DateTime dt = Convert.ToDateTime(s, CultureInfo.InvariantCulture);
w.WriteLine(dt);
Which should now make it obvious that you are not using InvariantCulture to display the date, it uses the default culture. Which on your machine puts the day first.
Always write readable code, it is not slower.
CultureInvariant only guarantees that the format won't change across cultures - it should not be used to display data, only to persist data. If you're concerned about how a string is displayed, you should use a specific culture that displays how you want. More from MSDN
Having said that, I'm not sure what you mean by a "date slipping by" in a different format. Are you reading a list of dates, and some are in different format? If so, I'm afraid CultureInvariant is not the answer.

convert string in unknown format to date in c#

I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats,
eg.
dd/MM/yyyy
MM/dd/yyyy
MM-dd-yyyy
dd-MM-yyyy
dd/MM/yyyy hh:mm::ss
MM/dd/yyyy hh:mm::ss
etc...
But I need to convert in to a common format - dd/MM/yyyy. The application can run in any windows machines in different culture.
What is the correct way to do it?
EDIT: One more thing I may not know what the format of incoming string.
Thanks in advance.
Use DateTime.ParseExact with the different patterns as formats.
If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.
You could distinguish between those formats that use different separators (i.e. "/" vs "-"). But how would you know if date such as 10/11/2010 represents 10th of November or 11th of October? If one number is not bigger than 12, there is no reliable way to do this without knowing an exact format.
As others have pointed out, if you do know the exact format, then you can use DateTime.ParseExact.
If you are processing some import file with a lot of dates in the same unknown format, you could try different formats and hope there is exactly one that doesn't give format errors.
Or to put it another way: split the "dates" into three numbers and check the range of values for each of those numbers. Values > 1900 will be years. If you find values from 1 to 31, those will be days.
Values from 1 to 12 might be months, but could also be days. Try and identify each of the parts.
The best way is to ask the supplier of those dates for the format.
To run this program on different culture, i think you should creat a function to indentify the culture of this string format and then use Datetime.Parse

datetime.parseexact returns wrong month

Here is my code:
a.dateFrom = DateTime.ParseExact(x, "dd/mm/yyyy", null);
And x has value of: 08/03/2012
However, a.dateFrom has value of 08/01/2012. Why?
You should use MM as format for month
As ionden notes, you should have a format of
"dd/MM/yyyy"
Currently you're parsing the second part as minutes (as that's what mm means).
See the documentation for custom date and time format strings for more information. I'd also strongly encourage you to consider using the invariant culture for parsing - if you're using a custom format string, that usually means you don't want to treat the input in a culture-sensitive fashion at all.

Change date to Universal Time Format changes my date wrongly I can't get error

I am trying to simply change the date format from the datatable to universal time format but it formats it wrongly as if I have date for August 7 it changed it to August 8 after formatting it to universal date time. My code for formatting date is,
DateVar[runs] = DateTime.Parse(Convert.ToString(output.Tables[0].Rows[runs][0])).ToUniversalTime().ToString();
Don't get in to code its correct and its a part of loop so "run" is loop and output is data set having one table I have first data in table is "Sunday, August 07, 2011 10:52 PM" and it was converted to "8/8/2011 5:52:00 AM" after implementing universal time format.
Hopes for your suggestions
Universal time isn't a format - it's a time zone, effectively. It's not clear what you're trying to do, but converting a "local" DateTime to "universal" DateTime will usually change the time. If you don't want that to happen, don't call ToUniversalTime.
It's a pity that the .NET date/time API isn't as clear as it could be - the DateTime type itself has some horrible ambiguities about it. I'm trying to improve the situation with my Noda Time project, but you will need to understand what time zones are about etc.
Personally I would suggest not using simply DateTime.Parse or just calling ToString unless you're absolutely sure that the default format is what you want. I usually call DateTime.ParseExact and specify the expected format (and usually CultureInfo.InvariantCulture unless it's a user-entered string) - and likewise I provide a format string to the ToString call.
In your code you're simply converting a string to a string - what are you attempting to accomplish? If you're just trying to change the format (e.g. to dd/MM/yyyyTHH:mm:ss) then you don't need to call ToUniversalTime but you do need to provide the format string.
I suggest you split your code out into several statements to help you debug this (and for general code clarity):
Fetch the string from the DataTable, if you really need to (if it's already a DateTime, there's no point in converting it to a string and then back again)
Parse the string (again, assuming you need to)
Perform any conversions you need to
Format the DateTime with an explicit format string
Now if any single operation is causing a problem, you can isolate it more easily.
If I run ToUniversalTime() from Greenwich it will give same time but if i do it while I live some where else it will get an offset date time object of + or - hours depending on position.

datetime.parse and making it work with a specific format

I have a datetime coming back from an XML file in the format:
20080916 11:02
as in
yyyymm hh:ss
How can I get the datetime.parse function to pick up on this? Ie parse it without erroring?
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As #Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Categories

Resources