How can I read a text file of dates and convert them to an array that I can sort in C #?
I have a date text file that looks like this:
16/02/2015 13/02/2015 12/02/2015 11/02/2015 10/02/2015 09/02/2015
etc.
How can I convert this to something I can use in quicksort for example? I am already reading a text file like this
string[] Date = System.IO.File.ReadAllLines("Date.txt");
I've tried using something like this:
double[] Dates = Array.ConvertAll(Date, s => DateTime.Parse(s));
And it just doesn't work.
My desired output after entering my algorithm should be to have them in order, but output the same format as I did earlier.
Any advice would be greatly appreciated. Thanks for reading.
EDIT
So, I managed to get the dates displayed in such a way that I want to use this method:
string[] Date = System.IO.File.ReadAllLines("Date.txt");
DateTime[] Dates = Array.ConvertAll(Date, s => DateTime.Parse(s));
However, it also displays the time.
19/01/2014 00:00:00
How can I get rid of this?
Thanks again guys!
source to share
DateTime.ParseExact takes a string and format to parse into DateTime objects.
Using linq ...
dates.Select(p=> DateTime.ParseExact(p, @"dd/MM/yyyy");
Should return a set of dates, which you can then sort.
source to share
You can try below snippet,
string[] Dates = File.ReadAllLines("Date.txt");
var sortableDates = Dates
.Select<string, DateTime>(d => DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture))
.ToArray<DateTime>();
Updated answer to match the modified question,
var sortableDates = File.ReadAllLines("Date.txt")
.Select<string, DateTime>(d => DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture))
.OrderBy<DateTime, DateTime>(d => d)
.Select<DateTime, string>(d => d.ToString("dd/MM/yyyy"))
.ToArray<string>();
Respond as per users implementation,
var result = Array.ConvertAll<string, DateTime>(Dates, d => DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture))
.OrderBy<DateTime, DateTime>(d => d)
.Select<DateTime, string>(d => d.ToString("dd/MM/yyyy"))
.ToArray<string>();
source to share
int ConvertDate(string date)
{
string day = "";
string month = "";
string year = "";
int count = 0;
foreach(char c in date)
{
if(count < 2)
day = day + c;
else if(count > 5)
year = year + c;
else if(c != '/')
month = month + c;
count++;
}
string tempDate = year + month + day;
return Convert.ToInt32(tempDate);
}
source to share