|
-
Jul 8th, 2008, 12:29 PM
#1
Thread Starter
Addicted Member
[RESOLVED] [2.0] Convert String to DateTime
I have a string with the month and year, separated by a "/". I need to convert this to a DateTime, but then convert it back to a string (don't ask, it's how the original developer made it). I have seen several examples on how to convert strings to DateTime, but none would work in this instance.
Code:
String date = "11/10";
DateTime dt = Convert.ToDateTime(date);
String result = dt.Month + "/" + dt.Year
This would return "11/08", I guess it thinks the 10 is the day instead of the year. How can I get this to work in my instance?
-
Jul 8th, 2008, 12:32 PM
#2
Fanatic Member
Re: [2.0] Convert String to DateTime
A date requires a year, month, and day. If you don't have all 3 parts, you can't make a date. I guess you could always just hard-code 1 in for the day:
Code:
String date = "11/10".Replace("/", "/1/");
DateTime dt = DateTime.Parse(date);
result = string.Format("{0}/{1}", dt.Month, dt.Year);
If your problem is solved, please use the Mark Thread As Resolved under Thread Tools!
Show Appreciation. Rate Posts!
-
Jul 8th, 2008, 12:40 PM
#3
Thread Starter
Addicted Member
Re: [2.0] Convert String to DateTime
Yes, that does work. Thank you.
-
Jul 8th, 2008, 06:47 PM
#4
Re: [RESOLVED] [2.0] Convert String to DateTime
This would be the "proper" way:
CSharp Code:
string s = "11/10"; DateTime d; if (DateTime.TryParseExact(s, "MM/yy", null, System.Globalization.DateTimeStyles.None, out d)) { MessageBox.Show(d.ToShortDateString()); } else { MessageBox.Show("Invalid date string."); }
If you want to you can call ToString instead of ToShortDateString and pass any format string you like, e.g.
CSharp Code:
MessageBox.Show(d.ToString("MM/yy"));
Note also that you should only use "MM/yy" if all single digit months are required to be padded with a leading zero. If they don't then you should use "M/yy", which will work for single or double digit months.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|