How to remove milliseconds and Culture Invariant?

Viewed 252

I have a variable which is expiryDate from object product. The property of the expiry date is as below:

public DateTime? ExpiryDate{ get; set; }

The date is returned in the following format:

2020-01-15 11:16:40.6071922

Because my DateTime for ExpiryDate is nullable, when I try something like this:

var expiry = DateTime.ParseExact(products.ExpiryDate, "yyyy/MM/dd HH:mm:ss", null);

I get the below error:

CS8604 - Possible null reference argument for parameter 's' in DateTime DateTime.ParseExact...

I can suppress the error, but this is not what I want to do. Is there anyway to remove the milliseconds without having to convert to string.

4 Answers

To remove milliseconds you can do:

 var expiry = products.ExpiryDate.AddMilliseconds(-products.ExpiryDate.Millisecond);

Generally, I use a static (extension) method like this

public static DateTime IgnoreTimeSpan(this DateTime dateTime, TimeSpan timeSpan)
{
    if (timeSpan == TimeSpan.Zero)
        return dateTime;

    return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}

public static DateTime? IgnoreMilliseconds(this DateTime? dateTime)
{
    if (!dateTime.HasValue) return dateTime;
    return dateTime?.IgnoreTimeSpan(TimeSpan.FromMilliseconds(1000));
}

and call it like this

DateTime? input;
DateTime? output;

input = new DateTime(2019, 9, 9, 10, 10, 10, 765);
output = input.IgnoreMilliseconds(); // output = "09/09/2019 10:10:10"

This will support you to reuse it more than one time

You wrote:

The date is returned in the following format...

Apparently you have some method that returns a string representation of a DateTime. If you want to convert a string to a DateTime is is usually better to use DateTime.Parse, instead of ParseExcact, because that will accept the text in several formats, even more if you use current culture as format provider.

In baby steps:

string dateTimeText = "2020-01-15 11:16:40.6071922";
DateTime dateTime = DateTime.Parse(dateTimeText, CultureInfo.CurrentCulture);
DateTime? nullableDateTime = dateTime;

If you expect that the text sometimes cannot be parsed;

DateTime? nullableDateTime;
if (DateTime.TryParse(dateTimeText, out DateTime dateTime))
{
    // text could be parsed
    nullableDateTime = dateTime;
}
else
{
    nullableDateTime = null;
}

You can create a new DateTime.

This is necessary when you need to round more than one parameter.

var date = ExpiryDate.HasValue ? 
    (DateTime?) new DateTime(ExpiryDate.Value.Year, ExpiryDate.Value.Month,
        ExpiryDate.Value.Day, ExpiryDate.Value.Hour, ExpiryDate.Value.Minute, ExpiryDate.Value.Second) 
    : null;
Related