Assign datetime value to today's date with specific time - c#

I have a variable which is defined as a DateTime. I need to assign it today's date but have the time be 4 PM. How do I do this?

You want DateTime.Today.AddHours(16)
DateTime.Today will return today's date at midnight.
You can also use the Date property to drop the time from an arbitrary DateTime value.

I think this should do what you need...
DateTime today = DateTime.Today;
DateTime dt = new DateTime(today.Year, today.Month, today.Day, 16, 0, 0);

var anotherTime = DateTime.Today.AddHours(16.0);

Take a look at all the overloaded constructors for DateTime.
DateTime myDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 16, 0, 0);
Edit: Correction. Thanks Jon. :)

Related

How to set time to Zeros in DateTime?

Lets say I have the following DateTime variable
DateTime CurDate = '26/3/2014 12:00:00 AM';
I'm wondering how can I set the CurDate so that the value will become 26/3/2014 00:00:00 AM
Note that I still want the time, but with all zeros.
**P/S: The reason for having all zeros is because the datetime value stored in SQL Server is 26/3/2014 00:00:00.000. I need to cast CurDate to have all zeros in order to match database data
You can simply use
CurDate.Date and that will give you '26/3/2012 00:00:00'
Try to format DateTime:
DateTime dt = new DateTime(2014, 06, 21, 0, 0, 0);
Console.WriteLine(dt.ToString("dd.MM.yyyy HH:mm:ss tt"));
Result:
21.06.2014 00:00:00
More informations:
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
You could try this one:
// Parse the string you have, to create a datetime.
DateTime CurDate = DateTime.ParseExact('26/3/2014 12:00:00 AM',
"dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
// Create the datetime you want based on the CurDate
DateTime result = new DateTime(CurDate.Year, CurDate.Month, CurDate.Day, 0, 0, 0);
For more information about ParseExact please have a look here.
Nowhere, in SQL Server or in .NET dates hasn't any presentation. They are just an numeric value. Don't care about that, both the SQL Server and .NET so smart that can pass parameters without any confusion. Just pass parameters of the correct data type.
Use 24 Hour Format
DateTime CurDate = DateTime.Parse("3/26/2014 12:00:00 AM");
Console.WriteLine("12 Hour Format: " + CurDate.ToString("dd-MM-yyyy hh:mm:ss"));
Console.WriteLine("24 Hour Format: " + CurDate.ToString("dd-MM-yyyy HH:mm:ss"));
I know it's late but I think this was the proper answer for future references:
Console.WriteLine("Current Date with 0s on time part: " + DateTime.Now.ToString("yyyy-MM-dd 00:00:00.000"));
this.dtGelisSaati = DateTime.Now;
set curency time values
this.dtGelisSaati = DateTime.Today;
this ok. zero time values set.
Put .Date and get the date part with zero time part.
I use Linq as:
var list = Results.Where(x => x.ExpDate.Date >= From.Date && x.ExpDate.Date <= To.Date).ToList();

How to set time to midnight for current day?

Every time that I create a non-nullable datetime in my mvc3 application it defaults to now(), where now is current date with current time. I would like to default it to today's date with 12am as the time.
I'm trying to default the time in my mvc...but...the following isn't setting to todays date #12am. Instead it defaults to now with current date and time.
private DateTime _Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0);
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
How can I set to 12am for the current date for non-nullable datetime?
You can use the Date property of the DateTime object - eg
DateTime midnight = DateTime.Now.Date;
So your code example becomes
private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...
var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
I believe you are looking for DateTime.Today. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
Only need to set it to
DateTime.Now.Date
Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();
It shows
"2017-04-08 00:00:00"
on my machine.
Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.
double utcOffset= 10.0; // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;
var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);
Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:
return (dateOne.Value.Date - dateTwo.Value.Date).Days;
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00

Creating DateTime in C#

How would I dynamically create a DateTime object, that always has what the current month/day/year is, but always has the 16:00 time component?
You can do this:
var today = DateTime.Today.AddHours(16);
That should be whatever today is at 16:00 (4pm)
How about:
DateTime today = DateTime.Today;
DateTime Today16 = new DateTime(today.Year, today.Month, today.Day,
16, 0, 0)
That should use the year, month, day of today, and set time to 16:00 hours.

How to set only time part of a DateTime variable in C# [duplicate]

This question already has answers here:
How to change time in DateTime?
(29 answers)
Closed 9 years ago.
I have a DateTime variable:
DateTime date = DateTime.Now;
I want to change the time part of a DateTime variable. But when I tried to access time part (hh:mm:ss) these fields are readonly.
Can't I set these properties?
Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:
var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);
you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:
var newDate = oldDate.Date + new TimeSpan(11, 30, 55);
date = new DateTime(date.year, date.month, date.day, HH, MM, SS);
I'm not sure exactly what you're trying to do but
you can set the date/time to exactly what you want in a number of ways...
You can specify 12/25/2010 4:58 PM by using
DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");
OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:
DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);
The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.
It isn't possible as DateTime is immutable. The same discussion is available here: How to change time in datetime?

Getting the date only in Convert.ToDateTime() in asp.net

I have a parameter string that passes date value to a stored proc
cmdItemSearch.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#EndDate"].Value = Convert.ToDateTime(DateTime.Now);
The value being passed is "6/30/2010 7:45:00 AM"
I want to pass only "6/30/2010"
How would I do that?
For starters, DateTime.Now is already a DateTime so doesn't need to be converted as you have.
Secondly, you can obtain just the date of Today by using DateTime.Today instead of DateTime.Now.
However, if your date isn't "today" then you can just use yourDateTime.Date to return just the Date.
If you are looking for the mm/dd/yyyy format, you could use
DateTime.Now.ToShortDateString()
That will return the short format, but depends on the current culture
cmdItemSearch.Parameters["#EndDate"].Value = DateTime.Today;
Note that the Today property simply returns a DateTime with the time element set to midnight.
MSDN to the rescue: http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
Create a variable called EndDate
var EndDate = DateTime.Now.ToString("MM/dd/yyyy");
EndDate = Convert.ToDateTime(EndDate);
Now EndDate Type is DateTime;
you pass it as a parameter
cmdItemSearch.Parameters["#EndDate"].Value = EndDate ;

Categories