Click here to Skip to main content
16,010,268 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the date is store on textbox from datepicker.which formate is dd-mm-yyyy.

now i will try to get year form this formate.

What I have tried:

Console.WriteLine(TextBox1.Text);
DateTime dt1 =Convert.ToDateTime(Console.ReadLine());

int year = dt1.Year;

Console.WriteLine("The year in the date you entered: " + year);




Code o/p

textbox1.text=7-24-2016
dt1=01-Jan-01 12:00:00 AM
year=1
it's wrong o/p.
dt1 get wrong date or not getting date from textbox so my o/p is wrong.

Thank you.
Posted
Updated 24-Jul-16 19:35pm

use DateTime.ParseExact [^]

try like this

C#
string date = "7-24-2016";
       string strmonth = int.Parse( date.Split('-')[0]).ToString("00");
       string strday = int.Parse(date.Split('-')[1]).ToString("00");
       string stryear = date.Split('-')[2];
       string strDate = string.Format("{0}-{1}-{2}", strmonth, date, stryear);
       DateTime dt = DateTime.ParseExact(strDate ,"dd-mm-yyyy",System.Globalization.CultureInfo.InvariantCulture);
       int year = dt.Year; // 2016
       int month = dt.Month; // 7
       int day = dt.Day; // 24



if you need only the year from the textbox and dont need the datetime object, you shall use this
C#
string date = "7-24-2016";
      int year = int.Parse( date.Split('-')[2]);
 
Share this answer
 
Comments
Vibhusha Devani 25-Jul-16 1:51am    
Thank You so much.it's very helpfull...!
Karthik_Mahalingam 25-Jul-16 2:06am    
welcome :)
C#
var strDate = "7-24-2016";

var arrDate = strDate.Split('-');

if (arrDate.Length == 3)
{
    Console.WriteLine(arrDate[arrDate.Length-1]);
}
 
Share this answer
 
Comments
Vibhusha Devani 25-Jul-16 1:33am    
Thank You so much.it's working proper on my code.very helpfull....!

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