Reputation: 351
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.
Upvotes: 3
Views: 1676
Reputation: 17556
something like below
DateTime? dt = null;
int pYear = 2012; // assuming pYear is getting populated from somewhere
int finalYear = 1900; // initilizing some value to it;
if (!(dt.HasValue))
dt = DateTime.Now;
var year = dt.Value.Year;
var pValue = "1-Apr";
if (pYear > year)
finalYear = pYear - 1;
else
{
finalYear = year;
}
return pValue + finalYear.ToString();
Upvotes: 0
Reputation: 155205
Just call DateTime.Parse
or DateTime.ParseExact
, never parse dates yourself because you will have a bug in your implementation. It's one of life's certainties, like death and taxes.
If you use Parse
and not ParseExact
be sure to specify a CultureInfo
because 03/06/99
will be parsed differently if the current locale is English (United States) as opposed to English (United Kingdom).
Upvotes: 0
Reputation: 6434
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;
}
Upvotes: 1
Reputation: 2884
If you want to convert a string to a date, then you should use the DateTime.Parse
method. You should probably declare the parameter as a string
, not DateTime?
.
Upvotes: 0