Parsing strings that contain time values to a DateTime value - c#

I have strings likes this:
' 630AM' , '1234PM' , '1000 '
These are the values saved in my Database.
And I want to parse them to a date time format, the Date part I don't care, can append a dummy date.
One way is to just have a bunch of if-else and string processing commands to solve it but I feel like we should some how be able to use DateTime.TryParseExact and do it in a cleaner way.
What do you suggest to be done along those lines?

This is how I would handle these:
public DateTime convert(string date)
{
int hour = int.Parse(date.Substring(0, 2));
int minute = int.Parse(date.Substring(2, 2));
if (hour < 12 && date.Substring(4, 2) == "PM")
{
hour = hour + 12;
}
return new DateTime(2014, 1, 10, hour, minute, 0);
}

Related

rounding to a specific 12hr timeframe in c#.net

I realize this may have been answered before, and I may just not be searching for the answer properly, so my apologies if this is a duplicate. This is for a c# webform.
I've got a datetime, set to now, and rounded up the nearest 30 minutes:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
I'm splitting the datetime into its component parts, using M:YY tt (no preceding 0 on the month, two digit year, 12 hr am/pm)
DateString = dtNow.ToString("M/dd/yy");
TimeString = dtNow.ToString("h:mm tt");
What I want do to is simple, I want to see if that TimeString falls between 7:00pm and 5:59am, just need to round it to 6:00am of the following day (unless its past midnight, in which case 6:00am of that day).
Can anyone help me out, or at least point out where its already answered?
You should really stick to DateTime. What you want using string will always need to parse again that string into a DateTime to implement your logic.
A simple solution:
public static DateTime GetRoundedDate(DateTime originalDate)
{
if(originalDate.Hour > 19)
return originalDate.Date.AddDays(1).AddHours(6);
else if (originalDate.Hour < 6)
return originalDate.Date.AddHours(6);
return originalDate;
}
So now you may call:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
var rounded = GetRoundedDate(dtNow);
DateString = rounded.ToString("M/dd/yy");
TimeString = rounded.ToString("h:mm tt");
Just look at the time properties on your DateTime object.
if (dtNow.Hour >= 19 || (dtNow is tomorrow && dtNow.Hour <= 7)) {
//do your stuff
}
where "is tomorrow" is something like dtNow.Date == DateTime.Today.AddDays(1)

CLARION Date Conversion C# + DATE ADD/SUBTRACT

*(This is for ISV database so I am kind of reverse engineering this and cannot change) ...
How can I do the following date to int (visa/versa) conversion in C# ...
So Say the Date is:
5/17/2012
it gets converted to int
77207
in the database.
At first I thought this was a Julian date however it does not appear to be the case. I was fooling around with the method from Julian Date Question however this does not match up.
var date = ConvertToJulian(Convert.ToDateTime("5/17/2012"));
Console.WriteLine(date);
public static long ConvertToJulian(DateTime Date)
{
int Month = Date.Month;
int Day = Date.Day;
int Year = Date.Year;
if (Month < 3)
{
Month = Month + 12;
Year = Year - 1;
}
long JulianDay = Day + (153 * Month - 457)
/ 5 + 365 * Year + (Year / 4) -
(Year / 100) + (Year / 400) + 1721119;
return JulianDay;
}
Outputs 2456055 //Should be 77207
I've been using this SQL to do the conversion:
SELECT Convert(date, CONVERT(CHAR,DATEADD(D, 77207, '1800-12-28'),101))
and it appears to be accurate. How could I do this conversion in C# ? And can someone edify me as to what standard this is based on or is it simply a random conversion. Thanks in advance.
//TO int
var date = new DateTime(1800,12,28,0,0,0);
var daysSince = (DateTime.Now-date).Days;
//FROM int
var date = new DateTime(1800, 12, 28, 0, 0, 0);
var theDate = date.AddDays(77207);
This appears to be a Clarion Date:
the number of days that have elapsed since December 28, 1800
Allegedly to, Display Clarion Dates In Excel it only takes
subtracting 36161 from the value and formatting it as a date
If it is a linear formula, you should be able to calculate formula in the form of y=mx+b. You would need a minimum of two data points.
Here is the vb.net Code I use to convert Clarion Date to Julian Date:
Dim ldblDaysToSubtract As Double = 36161.0
mclsRevEmployeeRecd.BirthDate(istrBirthDate:=(CDbl(E1Row.Item("BIRTH_DT")) - ldblDaysToSubtract).ToString)
mstrBirthDate = Format(CDate(Date.FromOADate(CDbl(istrBirthDate)).ToString), "MM/dd/yyyy")

Converting a string to Date

In a part of my system, I have this situation: I will receive a string that represents a date and another string that represents a time.
I need to let these informations in DateTime. So, a made it:
string date = "17012012";
string hour = "103445";
date = string.Format("{0}/{1}/{2}", date.Substring(0, 2),
date.Substring(2, 2), date.Substring(4, 4));
hour = string.Format("{0}:{1}:{2}", hour.Substring(0, 2),
hour.Substring(2, 2), hour.Substring(4, 2));
DateTime example = new DateTime();
example = DateTime.Parse(string.Format("{0} {1}", date, hour));
Ok, but is it a good pattern? Are there a "more beautiful" way to do this?
You could use DateTime.ParseExact instead
e.g.
DateTime.ParseExact(date + hour, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture);
Take a look at the Parse and ParseExact DateTime methods in the MSDN documentation.
I think that also Parsing Dates and Times in .NET can help.
One way or another your program must parse this format.
I would have done like this:
string date = "17012012";
string time = "103445";
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
int day = Convert.ToInt32(date.Substring(0, 2));
int hour = Convert.ToInt32(time.Substring(0, 2));
int minute = Convert.ToInt32(time.Substring(2, 2));
int second = Convert.ToInt32(time.Substring(4, 2));
DateTime example = new DateTime(year, month, day, hour, minute, second);

Exact c# result of sql datediff

I'm trying to get the number of days (calculated byu datediff) in sql and the number of days in c# (calculated by DateTime.now.Substract) to be the same, but they return different results....
//returns 0
int reso = DateTime.Now.Subtract(expirationDate).Days;
vs
//returns 1
dateDiff(dd,getDate(),ExpirationDate)
In both cases, ExpirationDate is '10/1/2011 00:00:00', and the code and the DB are sitting on the same server. I want the return int to be the same. I suspect I'm missing something stupid... ideas??
dateDiff(dd,getDate(),ExpirationDate) Is doing a days comparison. DateTime.Now.Subtract(expirationDate).Days is doing a date and time
For example
SELECT dateDiff(dd,'10/1/2011 23:59:00' , '10/2/2011') returns one day even when only one minute apart.
If you want the same in C# you need to remove the time component
e.g.
DateTime dt1 = new DateTime(2011,10,1, 23,59,0);
DateTime dt2 = new DateTime(2011,10,2, 0,0,0);
Console.WriteLine((int) dt2.Subtract(dt1.Subtract(dt1.TimeOfDay)));
So in your case it would be something like
DateTime CurrentDate = DateTime.Now;
int reso = CurrentDate.Subtract(CurrentDate.TimeOfDay).Subtract(DateTime.expirationDate).Days;
I haven't tested it but I would not do
DateTime.Now.Subtract(DateTime.Now.Subtract.TimeOfDay)
Because the second call to Now wouldn't be guaranteeing to be the same as first call to Now
In any case Stealth Rabbi's answer seems more elegant anyway since you're looking for a TimeSpan not a DateTime
10/1/2011 is less than 1 day away from DateTime.Now. Since you're getting back a TimeSpan and then applying Days to it, you're getting back a TimeSpan that is < 1 day. So it'll return 0 Days.
Instead, just use the Date component of those DateTimes and it'll correctly report the number of days apart - like this:
DateTime now = DateTime.Now;
DateTime tomorrow = new DateTime(2011, 10, 1);
var val = (tomorrow.Date - now.Date).Days;
This will yield you 1 day.
I'm assuming you want the number of Total days, not the number of days from the largest previous unit. You'd want to use the TotalDays property. Also, you may find it easier to use the minus operator to do a subtraction
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime(2009, 1, 2);
TimeSpan difference = d1 - d2;
Console.WriteLine(difference.TotalDays); // Outputs (today):1001.46817997424

Convert formatted date string to DateTime(int,int,int,int,int,int) to pass into a function

I am comparing the time now to a time stored somewhere in a database. The time stored in the database is in the format of "yyyyMMddHHmmss". For example, the database may return 201106203354 for a stored time value. I am then using a function to compare the time now to the time read in from the database.
What I am doing now:
Create 6 int variables
Take the sub-string from the formatted date string and convert the sub-string to an int32.
Pass the 6 int variables to the function.
What I would like to do:
Rather than splitting up the formatted date-time string, and seperately creating and assigning six variables to pass to the function, I would like to know if there is some way to simply convert the formatted date-time string into DateTime.
Please see my code as it will help to explain what I clearly cannot ...
Pass time now along with time read from database:
Private void passTime()
{
string timeStamp;
int year, month, day, hour, minutes, seconds;
DateTime dt = DateTime.Now;
timeStamp = dt.ToString("yyyyMMddHHmmss");
year = Convert.ToInt32(timeStamp.Substring(0, 4));
month = Convert.ToInt32(timeStamp.Substring(4, 2));
day = Convert.ToInt32(timeStamp.Substring(6, 2));
hour = Convert.ToInt32(timeStamp.Substring(8, 2));
minutes = Convert.ToInt32(timeStamp.Substring(10, 2));
seconds = Convert.ToInt32(timeStamp.Substring(12, 2));
MessageBox.Show(GetDifferenceDate(
new DateTime(year,month,day,hour,minutes,seconds),
// Example time from database
new DateTime(2011, 08, 11, 11, 40, 26)));
}
static string GetDifferenceDate(DateTime date1, DateTime date2)
{
if (DateTime.Compare(date1, date2) >= 0)
{
TimeSpan ts = date1.Subtract(date2);
return string.Format("{0} days",
ts.Days);
}
else
return "Not valid";
}
So, quite simply, I would like to compare two dates that are both in the format of "yyyyMMddHHmmss", or if this is not possible, I would like to convert the previous Date string into a DateTime.
I'm sure I left something out here, I will go back and read it again but please feel free to ask me anything that I left unclear.
Thank you,
Evan
You're looking for ParseExact:
DateTime.ParseExact(timeStamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)

Categories