I import an excel file into a DataGridView, one of the columns in the excel file is named DATETIME and contains both the date and time, I need to separate the date from the time how can i actually do this

I've tried something but it just gives either the date only or the time only, but I needed it both separately.

Any help on this?

Recommended Answers

All 4 Replies

Assuming the text is in a standard format the DateTime structure has a TryParse method to convert text. The DateTime structure allows you to extract any or all parts of the date and/or the time.

If you are absolutely sure that DATETIME string always has the same format, yuo could use something like this:

const int DateStrLength = 5;
string DateTimeStr = "ADateATime";
string DateStr = DateTimeStr.Substring(0, DateStrLength);
string TimeStr = DateTimeStr.Substring(DateStrLength, DateTimeStr.Length - DateStrLength);

Now DateStr will contain the date part "ADate"and TimeStr will contain the time part "ATime".

Assuming it's a string; most date-time arrangments have a space as the separator. Try using a split like this:

string datatimeString = "06/02/2015 14:04:00";
var result = datatimeString.Split(' ');
Console.WriteLine("Date: {0}, Time: {1}", result[0], result[1]);

It's simple and gives you both date and time as separate string values:

Console: "Date: 06/02/2015, Time: 14:04:00"

Note that Excel might be using an OADate. If that's the case use:

DateTime myDate = DateTime.FromOADate(yourExcelOADate);
commented: Keen observation +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.