Extract Values from DateTime - c#

I'm working on an edit admin form and I'm populating two DropDownLists (hours and mins) from a DB. I need to extract the hours (12 hour format) and minutes from the returned DateTime object in the DB. Here's what I've tried:
DateTime dt = DateTime.Parse(biz.GetStartDateByID(classID).ToString());
int hrs = Convert.ToDateTime(dt.ToString()).Hour;
For "2012-03-08 22:45:00.000" in the DB, this gives "22" for hours. What's the best way of extracting the hours in 12 hour format and the minutes? For example, if the hours value in the DateTime object was "18", I'd need it as "6".

Try this:
String.Format("{0:hh}", dt);
This will give you the hour in 12-hour, zero-padded format.
For no zero-padding:
String.Format("{0:h}", dt);

int hrs24 = dt.Hour;
int hrs12 = hrs24 > 12 ? hrs24 - 12 : (hrs24 == 0 ? 12 : hrs24);

DateTime.Hour % 12
That will give 0-11 of course... do you want 1-12? If so:
((DateTime.Hour + 11) % 12) + 1
I don't think there's anything simpler built in...
you can visit this link also...
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Just use the proper format for DateTime to string conversion
DateTime dt = DateTime.Parse(biz.GetStartDateByID(classID).ToString());
int hrs = Convert.ToDateTime(dt.ToString("hh:mm:ss")).Hour;
For reference please look at this

Related

C#: Convert 3 Variables into 24 Hours Format

I'm new to C# and i need help on converting 3 int variables into 24 hour format. I look on other Stack Overflow questions but it mostly only convert 1 variable into DateTime meanwhile i need to convert 3 variables into to 24 hour format. Here's what the variable looks like
private int hours = 1;
private int minutes = 1;
private int seconds = 1;
my expected outcome is 01:01:01 but i don't know how to do that.
You can do it like this:
var dt= new DateTime(1, 1, 1, hours, minutes, seconds); // year, month, day, hours, minutes, seconds
If you want to cast to string after that, you can do:
dt.ToString("HH:mm:ss"); // 01:01:01 // 24 hour clock digits
dt.ToString("hh:mm:ss tt"); // 01:01:01 AM // 12 hour clock
I already found a answer that works for me since i can't insert the variables like the previous 2 answers. So i just use
hours.ToString("00")
minutes.ToString("00")
seconds.ToString("00")
this makes it into a string in 2 digit number like my expected outcome.

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)

How to take only the last 3 digits from the year

I have the windows form dateTimePicker. I want to take only the last 3 digits from the year for example: if the chosen date is 01.01.2016 i want it to be read as 0101016
The code i am trying to use wont work
string theDate = dateTimePicker1.Value.ToString("ddMMyyy");
When i put ddMMyyyy it looks like this: 01012016 what is ok,
when i put ddMMyy it gives this 010116 what is also ok
But i need it to give me the last 3 digits from the year and when i put ddMMyyy it wont work :/
DateTime dateTime = dateTimePicker1.Value;
string theDate = dateTime.ToString("ddMM") + dateTime.Year.ToString("D4").Substring(1);
You could use Substring to get the Year from the (n-3)-th digit onwards for year >= 1000 like this:
DateTime dt = dateTimePicker1.Value;
string y = dt.Year.ToString();
string val = dt.ToString("ddMM") + y.Substring(y.Length > 3 ? y.Length - 3 : 0);

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

how to get the 12 hour date from DateTime

when i get the DateTime.Hour property, i always get the 24 hour time (so 6PM would give me 18).
how do i get the "12 hour" time so 6PM just gives me 6.
i obviously can do the check myself but i assume there is a built in function for this.
How about:
DateTime.Hour % 12
That will give 0-11 of course... do you want 1-12? If so:
((DateTime.Hour + 11) % 12) + 1
I don't think there's anything simpler built in...
DateTime.Now.ToString("hh"); --> Using this you will get "06" for 18h.
I don't know of any built in method, but you can always add an extension method to accomplish this.
Of course, you could always replace the code with the way you want to accomplish it.
public static class Extension
{
public static int GetTwelveCycleHour(this DateTime dateTime)
{
if (dateTime.Hour > 12)
{
return dateTime.Hour - 12;
}
return dateTime.Hour;
}
}
What about simply:
public static int GetTwelveCycleHour(this DateTime dateTime)
{
return Convert.ToInt32(dateTime.ToString("h"));
}
There's no built-in function, mainly because you shouldn't need it:
If you're doing this for output to the user, look at using a format string.
If you're doing this for a calculation, you can subtract datetimes or add timespans directly.
Outside of this, the math calculation is simple enough and already available in other answers here.
I thought the most convenient answer was submitted by Jon Skeet. The below is the same but converted to Visual Basic. I like things to be super easy. It took me a few to figure out the C# to Visual Basic Conversion. I included some 'extra' stuff as well. Hope this saves someone else time.
Visual Basic
(((DateTime.Now().Hour + 11) Mod 12) + 1)
Extra
Dim stringDate = DateTime.Now().Year &
DateTime.Now().Month.ToString("00") &
DateTime.Now().Day.ToString("00") & "_" &
(((DateTime.Now().Hour + 11) Mod 12) + 1).ToString("00") &
DateTime.Now().Minute.ToString("00")
The ToString("00") forces each Month/Day/Hour/Minute to always be represented by two digits.
Year = 2019
Month: April 4 = 04
Day: 3 = 03
Hour: 10 = 10
5 Minutes = 05
stringDate = 201904031005
DateTime date = Convert.ToDateTime("12/12/2022 20:20:00 PM");
var hour = date.Hour;
var dateTime = Convert.ToDateTime((date.ToShortDateString() + " " + hour + ":00:00"));
Console.WriteLine(dateTime); // 12/12/2022 8:00:00 PM
Console.WriteLine(hour); // 20

Categories