Date time day/month (02/12) - c#

This seems like something I should be able to find on Google but I'm not having much look.
I'd like to format a date as day/month. Only thing I've found it {0:M} which displays the information I want however the month written out like December rather than "12". I need to use 02/12 if possible due to space restrictions.
Thanks for any help!

You could try the following format:
{0:dd/MM}

Have you simply tried:
myDateTime.ToString(#"dd/MM");

Are you sure its ignoring your local computer regional settings ?
What happens if you do:
Console.WriteLine(date1.ToString("M", CultureInfo.CreateSpecificCulture("en-US")));

Related

DateTime.Parse can format unusual format strings?

I was looking at a code in an application (Someone else wrote it),on some cases it worked fine and on some cases it gave exceptions,it was actually converting strings in datetime,here is the code
//5000 is the year,but what about "1" is it month or day ?,if its month
//then what about the day ?
DateTime time = DateTime.Parse("1.5000");//1.5000 doesn't looks a date to me ?
time.ToString();//returns "1/1/5000 12:00:00 AM"
//where as if I give this string to DateTime.Parse();
time = DateTime.Parse("2341.70");
//FormatException was unhandled
//String was not recognized as a valid DateTime.
A Confusing thought
How does this string "3.5000" (it matches the 1.5000 pattern) evaluates , does this means 3-3-5000 or 1-3-5000 ,the format is ambiguous its unclear and confusing !
My questions are,
What kind of formats can DateTime.Parse expects ?
Whats happening in the code above ?
Suggestions to improve the code ?
Many people have commented on the possible reasons for the parse that you have seen being successful but your question seems to have several separate parts...
1. What kind of formats can DateTime.Parse expects ?
DateTime.Parse has been written to be as inclusive as possible. Pretty much anything that it can find someway to make into a DateTime it will do its best to do so which means in addition to the usual familiar yyyy-MM-dd type formats more strange ones like M.yyyy or yyyy.M and so on.
2. Whats happening in the code above ?
That is very complicated because the DateTime.Parse method is itself very complicated. You can probably fidn the source code out there somewhere but the complexity made it very hard for me to follow. Without being able to give precise details I'm going to answer this the same as above. What is happening is that the framework is trying its best to give you a date back and not throw an exception. The date it gives is the best guess as to what you meant.
3. Suggestions to improve the code ?
It sounds like if you are getting parse exceptions that you are passing dates in formats that are unexpected. Without knowing what those inputs are its hard to say. Two things could improve your code though. Making sure a single consistent date format is used and then using DateTime.ParseExact to ensure that it conforms to the right format. You will remove all ambiguity this way but you will sacrifice flexibility.
The second option is to use DateTime.TryParse. This will attempt to parse your date and then return a boolean saying whether it succeeded or not. If successful the date parse will be returned in a ref parameter. This won't make your code any better at recognising unknown date formats but will let your code know when such an unparsable format crops up and you can deal with it (eg by providing user feedback reporting the wrong format and suggesting a correct one, or just by logging it or something else).
What the best method is depends mostly on where your input is coming from. If it is user input then I'd go with the second option. If it is automated input then you probably want to make sure your input is standardized and then use the first option. Of course circumstances always vary so this is not a hard and fast rule. :)
In regards to "2. Whats happening in the code above ?":
In some cultures, the date separator is a dot instead of a slash. So for example 13.12.2013 is a valid date (2013-12-13) in the format "dd.MM.yyyy". Now by whatever design choice, the day part in this example is not mandatory and if left out, is automatically filled with 1. So parsing 12.2013 would result in 2013-12-01. And therefore it's easy to see how 1.5000 would become 5000-01-01. 2341.70 can not be parsed, because 2341 is not a valid month. - So in this case 1.5000 is a "valid" date in the format M.yyyy.

Formatting date (time) in a string

I have a very stupid question.
When the end-user plans an action, the planned time must be visible on the usercontrol of the action like this (hh:mm). On every site I find about formatting dates into a string, they say to use {0:h} or {0:hh}. In my following code I do the same thing, it just doesn't work.
When the end-user plans an action, the returned string is now "Planned Start Date - HH:DD".
lblStartDatePlanned.Content = String.Format("Planned Start Date - {0:hh}:{1:dd}", date.Hour, date.Minute);
Object date is of type DateTime.
Anyone knows what is wrong? I don't want to waste too much time on such a small thing.
Thanks!
Use:
lblStartDatePlanned.Content = String.Format("Planned Start Date - {0:HH:mm}", date);
Generically, if you're trying to force 2 digits in a format string, you can also use:
String.Format("Planned Start Date - {0:00}:{1:00}", date.Hour, date.Minute);
Although, #Alessandro's answer is correct for your problem.
Try following:
lblStartDatePlanned.Content = date.ToString(#"hh\:mm");

Update Path Automatically at date change ?

my program is watching a text file log - generated each day automatically.
now when the day change my program keep using the last day file path,
is there a way to do so without checking that the datetime.day each time and equal it to the day when the app launched at?
i saw SystemsEvent.TimeChanged but it only work when the user change the date manualy,
thanks.
The simple way to do this is make your path using a DateTime object. For example;
string fp = #".\subdir\otherSubdir\somefile-" + DateTime.Now.ToString("MM-dd-yyyy") + ".log";
Of course I don't know what the format of your date is. Docs on format specifiers for DateTime's ToString method can be found here; http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
As pointed out in the comments you could also use a FileSystemWatcher however, that is quite a bit more complicated and likely unnecessary here. If you're looking for a more general solution (something that could work with files that use different naming conventions) that would be the way to go.

How to validate string is correct date time

I have some data picked up from an excel file.
I want to validate that the user has entered a valid date time string. I have tried to use DateTime.Parse method but found that certain values seem to be accepted.
For example,
If I submit 3.3 as a date time this is accepted by the DateTime.Parse method as a valid date time and outputs 03/03/2012 00:00:00
I want to want to block this. Only allowing the user to enter correctly formatted date times.
So for example a user could supply 03/03/2012 or 03/03/2012 12:30:00 but not values like 01022012 or 3.3.2012
Any Ideas?
You want to use DateTime.ParseExact or DateTime.TryParseExact
This allows you do parse from a date format string of your choice.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx
Examples here:-
http://msdn.microsoft.com/en-us/library/ms131044.aspx
You can use RegEx to to this. Something like this should help #"\d{2}/\d{2}/\d{4}(\s+\d{2}\:\d{2}\:\d{2})?"
You can handle it on the client side with various jquery plugin/functions like this or a simple Google search can return many other useful results.
if you want to handle it on the server side, (I am not sure on what project you are working) but depending over it you can write your own method/use Regex or Data Annotation MVC.
If you are still having trouble try adding few details about your project such as Language, Architecture etc. that would help more in providing the right solution.
Hope it helps. Thankyou

DateTime and Currency Globalization

I am working on converting an app for a UK customer to deploy on their server. I am trying to figure out the best way to make as few changes as possible to the app but still have the DateTime and currency values convert to UK format?
Any ideas? I am looking for something quick and light?
I would replace all the date references with DateTime.ParseExact and Currency references with moneyDouble.ToString("c").
//I would use ParseExact over Parse when dealing with global date conversions
DateTime dt = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
Double money = 100.00;
money.ToString("c");
There is obviously more elegant solutions but if you are looking for something quick and low impact.....
Extra Reading about System.Globalization should give you some extra info if needed.
Make sure you have the application set up with the proper culture. Add to that the suggestions BTHB suggested and you are pretty much on track here.
If you want to research, MSDN has some good articles on globalization/localization. Focus more on the localization part.

Categories