user15930341
user15930341

Reputation: 46

Format DateTime to specific format

When this function is called, it creates a text file with these attributes. There is one attribute known as start_date. When I convert to DateTime, the date format will be MM:DD:YYYY and an error will be shown. I am not sure how to change the format to DD:MM:YYYY, I have also read on the DateTime formatting but I still do not understand. Thanks.

Code is as follows:

static void generateInfoForITDepartment()
{
    string filepath = @"C:\Users\notgivingmydirectory\HRMasterlist.txt";
    List<Employee> people = new List<Employee>();
    List<string> lines = File.ReadAllLines(filepath).ToList();
    foreach (var line in lines)
    {
        string[] entries = line.Split('|');

        Employee newIT = new Employee();

        newIT.Nric = entries[0];
        newIT.FullName = entries[1];
        newIT.Start_Date = Convert.ToDateTime(entries[3]);
        newIT.Department = entries[5];
        newIT.MobileNo = entries[6];

        people.Add(newIT);
    }
    List<string> output = new List<string>();
    foreach (var it in people)
    {
        output.Add($"{ it.Nric }, { it.FullName }, { it.Start_Date }, { it.Department }, { it.MobileNo }");
    }
    File.WriteAllLines("ITDepartment.txt", output);
    Console.WriteLine("ITDepartment.txt has been created");
}

Edit: My textfile currently looks like this:

S1234567A|Jan Lee|Ms|05/10/1990|Software Architect|IT Department|98785432|PartTime|3500

S1234567B|Feb Tan|Mr|10/12/1991|Corporate Recruiter|HR CorporateAdmin|98766432|PartTime|1500

S1234567C|Mark Lim|Mr|15/07/1992|Benefit Specialist|HR Corporate Admin|98265432|PartTime|2900

Upvotes: 0

Views: 191

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

We need to use an option to parse the date from a specific format. While where here, let's improve the structure a bit, and the performance and memory use a LOT (what you had was grossly memory inefficient):

static IEnumerable<Employee> readEmployees(string filePath)
{
    var lines = File.ReadLines(filepath);
    return lines.Select(line => {
        var data = line.Split('|');
        var result = new Employee();
        result.Nric = data[0];
        result.FullName = data[1];
        result.Start_Date = DateTime.ParseExact(data[3], "dd/MM/yyyy", CultureInfo.InvariantCulture);
        result.Department = data[5];
        result.MobileNo = data[6];
        return result;
    });
}

static void generateInfoForITDepartment()
{
    string filepath = @"C:\Users\notgivingmydirectory\HRMasterlist.txt";
    var people = readEmployees(filePath);
    // note the extra format specifier for the date value
    var output = people.Select(emp => $"{ emp.Nric }, { emp.FullName }, { emp.Start_Date:d }, { emp.Department }, { emp.MobileNo }");

    File.WriteAllLines("ITDepartment.txt", output);
    Console.WriteLine("ITDepartment.txt has been created");
}

FWIW, I would also tend to update the Employee class to move some of this code to a ToString() override and a static Parse() method, which could let you simplify the code like this:

static IEnumerable<Employee> readEmployees(string filePath)
{
    var lines = File.ReadLines(filepath);
    return lines.Select(line => Employee.Parse(line));
}

static void generateInfoForITDepartment()
{
    string filepath = @"C:\Users\notgivingmydirectory\HRMasterlist.txt";
    var people = readEmployees(filePath);

    File.WriteAllLines("ITDepartment.txt", people); //calls the default ToString() 
    Console.WriteLine("ITDepartment.txt has been created");
}

Upvotes: 0

Krishna Varma
Krishna Varma

Reputation: 4250

Since the data is not a valid date format, you need ParseExact or TryParseExact. If you are sure about incoming format is always in dd/MM/yyyy, then use ParseExact

Here is the example with ParseExact

newIT.Start_Date = DateTime.ParseExact(entries[3], "dd/MM/yyyy", CultureInfo.InvariantCulture);

Another example with TryParseExact

DateTime start_date = DateTime.MinValue;
var isValidDate = DateTime.TryParseExact(entries[3], "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out start_date);
newIT.Start_Date = isValidDate ? start_date : DateTime.MinValue;

Upvotes: 2

Related Questions