Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert sql function to c#

Hi all I am having an sql function where some part of it is used to convert varchar to datetime:

IF @dt IS NULL
    SET @dt = GETDATE();

SET @PDate = CONVERT(DATETIME, @PValue + '-' + CONVERT(NVARCHAR(4),YEAR(@dt))); 
IF @PDate > @dt
    SET @Year = YEAR(@dt) - 1;
ELSE
    SET @Year = YEAR(@dt);

RETURN (SELECT CONVERT(DATETIME, @PValue + '-' + CONVERT(NVARCHAR(4),@Year)));

Can some one help me?

My value of @PValue is 01-APRIL.

I just declare Datetime as follows in my C# code:

DateTime? dt=null;

if(!(dt.HasValue))
    dt=DateTime.Now;

But after this I was confused to do the remaining.

like image 849
Learner Avatar asked Jul 31 '26 07:07

Learner


1 Answers

You could do with a year field in order to convert properly, I can't see 01-APRIL being a valid date. 01-APRIL when? Once you have a valid structured datetime, your C# code will read:

string pValue = @"01/04";
DateTime dt = new DateTime();
DateTime now = DateTime.Now;
pValue += string.Format(@"/{0}", now.Year);
int year = 0;
if (DateTime.TryParse(pValue, ref dt))
{
  if (dt > now)
    year = dt.Year -1
  else
    year = dt.Year;
}
like image 91
LukeHennerley Avatar answered Aug 01 '26 21:08

LukeHennerley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!