CadaMerx
CadaMerx

Reputation: 127

Convert portion of string to datetime in C#

I have two parameters defined in appsettings.json of an asp.net core project.

  "TimeParam": {
    "StartTime": "00:00:00.0001",
    "EndTime": "23:59:99.999"
    "BackOffDay": 1
  },

In a function, I need to pass two parameters as startDate and endDate of data type date.

For example, for the startDate I need to be like 17/06/2020 00:00:00.0001 and the endDate to be like 17/06/2020 23:59:99.999

How can I get to set the two variable as follows taking into consideration the time that I have set in the appsettings.json?

StartDate: DateTime.Now.AddDays(BackOffDay) EndDate: DateTime.Now

Upvotes: 0

Views: 1247

Answers (2)

Christoph Sonntag
Christoph Sonntag

Reputation: 4629

You tricked me a second there, 23:59:99.999 is no parseable time as there are only 59 seconds in a minute.

But here you go:

using System;           
using System.Globalization;
public class Program
{
    public static void Main()
    {
        var start= "00:00:00.0001";
        var end = "23:59:59.999";
        int backOffDay = 1;
        
        var startTimeSpan = TimeSpan.Parse(start);
        var endTimeSpan = TimeSpan.Parse(end);
        
        var startTime = DateTime.Now.Date.AddDays(backOffDay).Add(startTimeSpan);
        var endTime = DateTime.Now.Date.AddDays(backOffDay).Add(endTimeSpan);
        
        Console.WriteLine(startTime.ToString("dd/MM/yyyy H:mm:ss.FFFF"));
        Console.WriteLine(endTime.ToString("dd/MM/yyyy H:mm:ss.FFFF"));
    }
}

You can test it with this fiddle.

19/06/2020 0:00:00.0001

19/06/2020 23:59:59.999

P.S.: To make sure all timestamps are always parsed the same, you might want to do something like this as well:

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");

or just for a single call:

var culture = new CultureInfo("en-US");
var startTimeSpan = TimeSpan.Parse(start, culture);

Although parsing seemed to work well with en-US culture I wouldn't guarantee it does in all enivronments.

Upvotes: 4

JonasH
JonasH

Reputation: 36351

Use DateTime.Now.Date, then add the start and end time to create the start date and end date respectively. Use TimeSpan.Parse to parse the times.

(DateTime.Now.Date + TimeSpan.Parse("13:01:05")).ToString();
//2020-06-18 13:01:05

Upvotes: 2

Related Questions