DateTime operations in c#

Convert date in excel – to string – to date

In data driven environment, it’s common to read the data from excel and insert in the front end / back end, depending on the context.

The method that used here will return the date in the short Date Time format, so that you can use in the way you want to use. When storing date in the excel, make sure that the date is stored in this format in Excel.

public static DateTime ExtractDateFromExcel(string dateString) {

//OutPut will be DateTime with the format 31/12/2016 11:22:56 AM

var dateConverted = DateTime.ParseExact(dateString, "dd/MM/yyyy hh:mm:ss tt",null);

// Converting the DateTime to String format 31/12/2016

var shortDate = dateConverted.ToString("dd/MM/yyyy");

//Converting the string to DateTimeFormat 31/12/2016

dateConverted = DateTime.ParseExact(shortDate, "dd/MM/yyyy", null);

return dateConverted;

//Simple use like this

var day = dateConverted.Day;

var month = dateConverted.Month;

var year = dateConverted.Year;

Console.Write("Day " + day + "     Month " + month + "         Year : " + year);

}


 

 

To convert date  in “int” format to string.

 

Suppose if the date is stored in front as day, month, year like this

We need to convert that to string or DateTime, you can use the following methods

// This method will return the date in string format.

public static string GetDateForExcel(int year, int month, int day) {

var date = new DateTime(year, month, day);

return date.ToString("yyyy/MM/dd");

}


 

 

// This method will return the date DateTime format

public static DateTime GetDateForExcel(int year, int month, int day) {

var date = new DateTime(year, month, day);

return date;

}

 

 

To get the day in “00” format

var day = dateTime.Day.ToString("00");

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *