I want to separate the year from the Birthdate.I have a checkbox called Birthdate inside a modalpopup and it used to show the birthdate of a person beside the checkbox and when checked it will show the mm/dd/yy in a table created dynamically. But I want to separate开发者_高级运维 the mm/dd and the year and show only the date along with the month. And there will be another checkbox called Show year which will only show if the Birthdate checkbox is checked and if checked it will show only the year. For eg: if suppose birthdate is checked,it will show as below Birthdate [12/27] Year [1986] and if bithdate is not checked it will not show the year checkbox below
You can parse it with DateTime, then format it back out however you want. This assumes the data is coming from a database or similar, so it throws an exception for invalid data.
DateTime parsed = DateTime.ParseExact(birthDate, "MM/dd/yy", null);
string dateNoYear = parsed.ToString("MM/dd");
string year = parsed.ToString("yy");
If you have a DateTime
object (and you should, as opposed to dealing with dates as strings), then you can either:
- Query for the properties as integers:
myDate.Year
,myDate.Month
. - Format the date as a string:
myDate.ToString("yyyy");
,myDate.ToString("MM/dd");
You can review the DateTime string formatting options in MSDN here.
//Assuming you have your birtdate is in instance birthDate of type DateTime.
DateTime birthDate;
//set the birthDate here.
string year = birthDate.ToString("yyyy");
string month = birthDate.ToString("mm");
string day = birthDate.ToString("dd");
//Now play as you wish
Some more formatters you can use.
/**
*
* d :08/17/2000
* D :Thursday, August 17, 2000
* f :Thursday, August 17, 2000 16:32
* F :Thursday, August 17, 2000 16:32:32
* g :08/17/2000 16:32
* G :08/17/2000 16:32:32
* m :August 17
* r :Thu, 17 Aug 2000 23:32:32 GMT
* s :2000-08-17T16:32:32
* t :16:32
* T :16:32:32
* u :2000-08-17 23:32:32Z
* U :Thursday, August 17, 2000 23:32:32
* y :August, 2000
* dddd, MMMM dd yyyy :Thursday, August 17 2000
* ddd, MMM d "'"yy :Thu, Aug 17 '00
* dddd, MMMM dd :Thursday, August 17
* M/yy :8/00
* dd-MM-yy :17-08-00
*/
if (!Convert.IsDBNull(oReader["BIRTH_DATE"]))
lblBirthDate.Text = "[ " + Convert.ToDateTime(oReader["BIRTH_DATE"]).ToShortDateString() + " ]";
DateTime dob = Convert.ToDateTime(oReader["BIRTH_DATE"]); int year = dob.Year; lblBirthYear.Text += year; }
精彩评论