You are on page 1of 3

using System;

using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DateTimeProgram
{
public class DateTimeProcessor
{
private List<DateTime> dates;

public DateTimeProcessor()
{
dates = new List<DateTime>();
}

public void LoadDatesFromFile(string filePath)


{
try
{
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
DateTime date;
if (DateTime.TryParse(line, out date))
{
dates.Add(date);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}

public void SortDatesAscending()


{
dates.Sort();
}

public void SortDatesDescending()


{
dates.Sort();
dates.Reverse();
}

public void RemoveDuplicates()


{
dates = dates.Distinct().ToList();
}

public void AddDate(DateTime date)


{
dates.Add(date);
}

public void RemoveDate(DateTime date)


{
dates.Remove(date);
}

public void ResizeDates(int newSize)


{
if (newSize < 0 || newSize == dates.Count)
{
return;
}
else if (newSize > dates.Count)
{
for (int i = 0; i < newSize - dates.Count; i++)
{
dates.Add(DateTime.MinValue);
}
}
else
{
dates.RemoveRange(newSize, dates.Count - newSize);
}
}

public void PrintDatesToConsole()


{
foreach (DateTime date in dates)
{
Console.WriteLine(date.ToString("yyyy/MM/dd"));
}
}

public void WriteDatesToFile(string filePath)


{
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
foreach (DateTime date in dates)
{
writer.WriteLine(date.ToString("yyyy/MM/dd"));
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}

class Program
{
static void Main(string[] args)
{
DateTimeProcessor processor = new DateTimeProcessor();
processor.LoadDatesFromFile("dates.txt");
processor.PrintDatesToConsole();
processor.SortDatesAscending();
processor.PrintDatesToConsole();
processor.SortDatesDescending();
processor.PrintDatesToConsole();
processor.RemoveDuplicates();
processor.PrintDatesToConsole();
processor.AddDate(DateTime.Now);
processor.PrintDatesToConsole();
processor.RemoveDate(DateTime.Now);
processor.PrintDatesToConsole();
processor.ResizeDates(10);
processor.PrintDatesToConsole();
processor.ResizeDates(5);
processor.PrintDatesToConsole();
processor.WriteDatesToFile("sorted_dates.txt");
}
}
}

You might also like