Reputation:
Ok, so I have a date stored as an int in the format ddmmyy or dmmyy, with leading 0's cut off, e.g. 10914 or 100914
This value is 0 under certain conditions to represent 000000.
How would I convert this to DateTime without converting to a string first (due to the possibility of it being 0)? Is there some sort of DateTime.Parse overload for it?
Upvotes: 2
Views: 2148
Reputation: 747
int UrInt = 000000;
GroupCollection groups = Regex.Match(UrInt.ToString(), @"^(?<DAY>[0-9]{1,2})(?<MONTH>[0-9]{2})(?<YEAR>[0-9]{2})$").Groups;
int month;
if (int.TryParse(groups["MONTH"].Value, out month) == false)
{
month = 1;
}
int day;
if (int.TryParse(groups["DAY"].Value, out day) == false)
{
day = 1;
}
int year;
string _tmp = groups["YEAR"].Value;
// If the year matches 80-99 it will be 19xx if the year matches 00-79 it will be 20xx
if (Regex.IsMatch(_tmp, @"^[8-9]{1}[0-9]{1}$"))
{
_tmp = String.Join("", "19", _tmp);
if (int.TryParse(_tmp, out year) == false)
{
year = 1979;
}
}
else
{
_tmp = String.Join("", "20", _tmp);
if (int.TryParse(_tmp, out year) == false)
{
year = 1979;
}
}
DateTime UrDateTime = new DateTime(year, month, day);
Not the best way, but i think, that will match ur search terms. ;)
NOTE
U have to correct the year match to ur needs @"^[8-9]{1}[0-9]{1}$"
Explain:
^ = Line beginning
[8-9]{1} = Match 1st digit 8-9
[0-9]{1} = Match 2cnd digit 0-9
$ = Line end
Hope this helps.
Upvotes: 0
Reputation: 560
You could use integer division and modulo functions to break out the three sections, then use use the DateTime(int, int, int) constructor to create your DateTime value. You will need to change your year into a full four-digit year at some point also.
Something like this:
int year = (date % 100) + 2000;
int month = (date / 100) % 100;
int day = (date / 100000);
DateTime result = new DateTime(year, month, day);
Upvotes: 6