patternjavascriptMinor
How could I do DateTime.Now.Date (from C#) in JavaScript?
Viewed 0 times
javascriptcoulddatenowhowfromdatetime
Problem
In C# I can use
This will give the current date, without the TimeSpan value ('00:00:00'). In JavaScript I did this:
But is so "ugly" that there must be a better, easier and clean way to do it.
DateTime dt = DateTime.Now.Date;This will give the current date, without the TimeSpan value ('00:00:00'). In JavaScript I did this:
var dt = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());But is so "ugly" that there must be a better, easier and clean way to do it.
Solution
It is not ideal, but you can do it this way...
There are multiple ways to make Dates in javascript. The format above will create a new Date based on "today"'s year, month, and date (think day of the month).
Technically you could also do this with a DateString, however "new Date(dateString)" is implementation dependent, and may have inconsistent behavior across different browsers.
And if making 2 Date objects makes you uncomfortable, you could always do the following:
var today = new Date();
var dateWithoutTime = new Date(today.getFullYear() , today.getMonth(), today.getDate());There are multiple ways to make Dates in javascript. The format above will create a new Date based on "today"'s year, month, and date (think day of the month).
Technically you could also do this with a DateString, however "new Date(dateString)" is implementation dependent, and may have inconsistent behavior across different browsers.
And if making 2 Date objects makes you uncomfortable, you could always do the following:
var today = new Date();
today.setHours(0); // or today.toUTCString(0) due to timezone differences
today.setMinutes(0);
today.setSeconds(0);Code Snippets
var today = new Date();
var dateWithoutTime = new Date(today.getFullYear() , today.getMonth(), today.getDate());var today = new Date();
today.setHours(0); // or today.toUTCString(0) due to timezone differences
today.setMinutes(0);
today.setSeconds(0);Context
StackExchange Code Review Q#31503, answer score: 6
Revisions (0)
No revisions yet.