Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have string like this "1217" and i want convert to datetime with format "MMYY",
so how to make
thx for all....
Posted
Comments
Maciej Los 26-Aug-15 6:55am    
1217 is in format MMYY. What's an issue?

Not 100% sure what this will come up with. It will most likely be 01 dec 2017. It depends on how you want to use it. If you use it as a range then you will have to also find the end of the month

C#
DateTime.ParseExact("1217", "MMYY", CultureInfo.InvariantCulture);


End of Month:
C#
DateTime.ParseExact("1217", "MMYY", CultureInfo.InvariantCulture).AddMonths(1).AddDays(-1);
 
Share this answer
 
try with MMyy
C#
DateTime.ParseExact("1217", "MMyy", CultureInfo.InvariantCulture);

There is no capital Y format in datetime formats!
Quote:
here are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
 
Share this answer
 
v2
DateTime doesn't have a format so there is no such thing as "datetime with format". The best you'll be able to do is to convert your 1207 string into an arbitrary datetime such as 1 Dec 2017 with the understanding that the day part is irrelevant.

C#
string s = "1217";
DateTime dt;
DateTime.TryParseExact("01" + s, "ddMMyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt);

// dt now represents 1st Dec 2017
// add 3 months
dt = dt.AddMonths(3);

// convert back to MMyy
s = dt.ToString("MMyy");
 
Share this answer
 
v3
string[] formats = { "MMyy" }
var dateTime = DateTime.ParseExact("1712", formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900