Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a date column in sql server which shows date as
'2022-09-11 10:12:48.830'

i have to find whether date is older than 24 hours in C# dotnet core.

I tried below code , but it gives error-
formatexception: string '2022-18-11 11:18:04:nnn' was not recognized as a valid datetime.

What I have tried:

string dt = DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss:nnn", CultureInfo.InvariantCulture);


c.CreateDatetime < Convert.ToDateTime(dt, CultureInfo.InvariantCulture).AddHours(-24)
Posted
Updated 11-Sep-22 8:22am
v6

1 solution

Don't convert dates to strings in order to convert them: convert strings to DateTime and compare those.
Equally, if it's a DATETIME, DATETIME2 or DATE column in SQL, then it automatically converts to a DateTime in C# (as it's stored in both as a number of ticks since a defined point in time).

Your code is failing because you are converting a DateTime to a string, and getting it wrong:
DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss:nnn", CultureInfo.InvariantCulture)
                            ^
                            |
The format code "mm" is the minutes, not the month: Formatting a DateTime for display - format string description[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900