How to set time to Zeros in DateTime? - c#

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();

Related

ASP.NET MVC convert DateTime to UTC to send to API

I need to send a start date and end date to an API in UTC format, I have tried the following:
DateTime startDate = Convert.ToDateTime(start + "T00:00:00Z").ToUniversalTime();
DateTime endDate = Convert.ToDateTime(end + "T23:59:59Z").ToUniversalTime();
But it appears they are not converting to UTC, what would be the proper way to take startDate and endDate and convert them over to UTC?
start is a string and is 2018-08-31 and end date is also a string and is 2018-08-31 I added the times in the code above to cover the full date.
Assuming you want endDate to represent the last possible moment on the given date in UTC:
DateTime startDate = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
DateTime endDate = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
.AddDays(1).AddTicks(-1);
A few other things:
ToUniversalTime converts to UTC from the computer's local time zone (unless .Kind == DateTimeKind.Utc). You should generally avoid it unless the computer's local time zone is relevant to your situation.
In the above code, you need both AssumeUniversal to indicate that the input date is meant to be interpreted as UTC, and AdjustToUniversal to indicate that you want the output value to be kept in terms of UTC and not the computer's local time zone.
UTC is not a "format". Your combined date and time strings would be in ISO 8601 extended format (also RFC 3339 compliant).
Generally, try not to use Convert.ToDateTime. It is equivalent to DateTime.Parse with CultureInfo.CurrentCulture and no DateTimeStyles. That may work for some scenarios, but it is usually better to be more specific.
.AddDays(1).AddTicks(-1) is there to get you to the last representable tick on that date. That allows for inclusive comparison between start and end, however it comes with the disadvantage of not being able to subtract the two values and get a whole 24 hours. Thus, it is usually better to simply track 00:00 of one day to 00:00 of the next day, then use exclusive comparison on the end date. (Only the start date should be compared inclusively.)
In other words, instead of:
2018-08-31T00:00:00.0000000Z <= someValueToTest <= 2018-08-31T23:59:59.9999999Z
Do this:
2018-08-31T00:00:00.0000000Z <= someValueToTest < 2018-09-01T00:00:00.0000000Z
First install below package from NuGet package manager and referenced it in your project:
Install-Package Newtonsoft.Json
Now you can easily use JsonConvert.SerializeObject(object value) method for serialize any objects to Json.
For converting DateTime to UTC use TimeZoneInfo.ConvertTimeToUtc(DateTime dateTime) method.
In your case:
DateTime date = DateTime.Parse("2018-08-31");
DateTime dateTimeToUtc = TimeZoneInfo.ConvertTimeToUtc(date);
string dateInJson = JsonConvert.SerializeObject(dateTimeToUtc);
the variable dateInJson will have value like 2018-08-30T19:30:00Z.
Remove the Z
string start = "2018-08-31";
string end = "2018-08-31";
DateTime startDate = Convert.ToDateTime(start + "T00:00:00");
DateTime endDate = Convert.ToDateTime(end + "T23:59:59");
Console.WriteLine(startDate); // 8/31/2018 12:00:00 (Local)
Console.WriteLine(startDate.ToUniversalTime()); // 8/31/2018 5:00:00 (UTC)
Console.WriteLine(endDate); // 8/31/2018 11:59:59 (Local)
Console.WriteLine(endDate.ToUniversalTime()); // 9/1/2018 4:59:59 (UTC)
In case you are sending dynamic linq like me, you'd need datetime in a text form.
If you are dealing with UTC then:
//specify utc just to avoid any problem
DateTime dateTime = yourDateTime.SetKindUtc();
var filterToSendToApi = $"CreatedTime>={dateTime.ToStringUtc()}"
helpers:
public static string ToStringUtc(this DateTime time)
{
return $"DateTime({time.Ticks}, DateTimeKind.Utc)";
}
public static DateTime SetKindUtc(this DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime;
}
return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}

un-representable DateTime

I have method which expects two datetime parameters
public void SomeReport(DateTime TimeFrom, DateTime TimeTo)
{
// ommited
TimeFrom.ToString("ddMMyy"), TimeTo.ToString("ddMMyy")));
// ommited
}
When I'm sending this params
DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = new DateTime().AddHours(-1);
This error occured:
System.ArgumentOutOfRangeException : The added or subtracted value results in an un-representable DateTime.
What can be the problem?
new DateTime() is 01/01/0001 00:00:00 which is also DateTime.MinValue.
You are subtracting one hour from that.
Guessing you are trying to subtract an hour from the TimeTo value:
var TimeFrom = TimeTo.AddHours(-1);
new DateTime() returns the minimum representable DateTime; adding -1 hours to this results in a DateTime that can't be represented.
You probably want DateTime TimeFrom = TimeTo.AddHours(-1);
try:
DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = TimeTo.AddHours(-1);
creating a DateTime with new DateTime() gives you a DateTime with DateTime.MinValue... from this you actually can't subtract anything... otherwise you get the exception you got... see MSDN
Look you date or time data .There not enough digits for date or time Example date must be 8 digit 20140604 and time 6 digit like this 180203.For this reason you are getiing error.
i get this error too and find time 18000 and change this to 180000 problem solved.
In your case TimeFrom holds the datetime from which -1 can not be added. You can either invoke
DateTime TimeFrom = TimeTo .AddHours(-1);
or
DateTime TimeFrom = new DateTime().now.AddHours(-1);
Both of them yield the same result.
In my error, I used the time as 24:00 instead of 00:00

Conversion to Time 12 hour Format From String containing Time in 24 hour format

I have a varchar(5) column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration.
For Example
8:18 should be converted into 8:18:00 AM and then should be embedded
with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime
column of DB.
22:20......10:20:00 PM.......8/10/2012 10:20:00 PM
The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012
You can do something like this:
string input = "22:45";
var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);
string timeIn12HourFormatForDisplay = timeFromInput.ToString(
"hh:mm:ss tt",
CultureInfo.InvariantCulture);
var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);
And now the important parts to take in consideration:
The format for parsing uses "H:m" so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;
The format for printing uses "hh:mm:ss tt" because it seems to be the format you desire, however you need to use CultureInfo.InvariantCulture to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;
The full date and time is constructed based on DateTime.Today which returns the today date with a zeroed time and then we just add the time we read from input.
To create the final date and time from another date you can instead use:
var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);
Reference material:
DateTime Structure;
Custom Date and Time Format Strings;
Standard DateTime Format Strings.
create function dbo.COMBINE_DATE_TIME(
#DatePart DateTime, -- DateTime
#TimePart varchar(5)) -- Time
returns DateTime
as begin
return DATEADD(day, DATEDIFF(day,0,#DatePart),
CONVERT(DateTime,ISNULL(#TimePart,''),14))
end
go
string strDate = DateTime.ParseExact("8:18","HHmm",CultureInfo.CurrentCulture).ToString("hh:mm tt");
string fromTime = Convert.ToStr(reader["TimeFrom"]);
string toTime = Convert.ToStr(reader["TimeTo"]);
item.Time=DateTime.Parse(fromTime,CultureInfo.CurrentCulture).ToString("hh:mm tt");
here the property of your model(item.Time here) should be the string.

extract the date part from DateTime in C# [duplicate]

This question already has answers here:
How to remove time portion of date in C# in DateTime object only?
(43 answers)
Closed 9 years ago.
The line of code DateTime d = DateTime.Today; results in 10/12/2011 12:00:00 AM. How can I get only the date part.I need to ignore the time part when I compare two dates.
DateTime is a DataType which is used to store both Date and Time. But it provides Properties to get the Date Part.
You can get the Date part from Date Property.
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"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));
// The example displays the following output to the console:
// 6/1/2008 7:47:00 AM
// 6/1/2008
// 6/1/2008 12:00 AM
// 06/01/2008 00:00
There is no way to "discard" the time component.
DateTime.Today is the same as:
DateTime d = DateTime.Now.Date;
If you only want to display only the date portion, simply do that - use ToString with the format string you need.
For example, using the standard format string "D" (long date format specifier):
d.ToString("D");
When comparing only the date of the datatimes, use the Date property. So this should work fine for you
datetime1.Date == datetime2.Date
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date
if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.
code snippet
DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
Console.WriteLine("d1 < d2");
else
if (d1.DayOfYear < d2.DayOfYear)
Console.WriteLine("d1 < d2");
you can use a formatstring
DateTime time = DateTime.Now;
String format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));

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