javascript Today() function - javascript

I'd like to determine if a given date object is the same day as the current day. Below is the psuedo code.
// date is a Date object
function (date)
{
if (date == Today())
alert('How are you today?');
else
alert('How were you last ' + date.toDateString() + '?');
}
How do I implement the Today() function? It doesn't have to be a function really, an equivalent solution will be just as good. Thanks.
[edit]
I forgot to mention. The current time (today) is local time and the date object that it will be compared with is server time, which can be anywhere in the world.

You can just compare the toDateString()s of the date string you're passing to a new Date() without any parameter passed to it (it will default to today).
// date is a Date object
function alertDateGreeting(date)
{
if (date.toDateString() == (new Date()).toDateString())
alert('How are you today?');
else
alert('How were you last ' + date.toDateString() + '?');
}

Use the following:
var today = new Date();
Keep in mind that the Javascript Date object is a timestamp despite its name. You will probably want to compare the individual fields for equality with getMonth(), getDate() and getFullYear(), as per the following sample:
<html>
<head>
</head>
<body>
<script language="javascript">
var today = new Date();
alert(
today.getFullYear() + "." +
(today.getMonth() + 1) + "." +
today.getDate()
);
</script>
</body>
</html>

This is an interesting question. First, you get the current datetime in JavaScript with
new Date()
However, comparing two dates is not really done with ==
Consider
> d = new Date(2011, 1, 1)
Tue Feb 01 2011 00:00:00 GMT-0800 (PST)
> d2 = new Date(2011, 1, 1)
Tue Feb 01 2011 00:00:00 GMT-0800 (PST)
> d == d2
false
But...
> d2 = new Date(2011, 1, 1).getTime()
1296547200000
> d = new Date(2011, 1, 1).getTime()
1296547200000
> d == d2
true
Because two date objects will be equal only if they are the exact same object. So when you compare dates, use getTime. If you are only concerned with the equality of dates and not date times, you have to do a little more work, but it is not so bad.
ADDENDUM:
The question asked for a way to talk about the current date.
Here you have two ways to go, at least.
From the datetime object, find the corresponding midnight time. There are algorithms for this, or you can use a package like date.js.
Hack it into a string: d.toISOString().substring(0,10). This is a ugly hack, and please, be careful about timezones!

There is no Today() method in javascript. You can use new Date() to get the current date.

Related

Javascript and setMonth behaving unexpectedly

I am doing datObj.setMonth(1), but the month is being set to March? Isn't 1 supposed to be February? I'm using Chrome 79.
Here's part of code meant to parse dates such as YYYY-MM-DD HH:MM:SS (because safari can't do that natively)
var date = "2020-02-02 23:59:00"
if (typeof date == 'string')
{
var dateParts = date.split(/[:-\s]+/);
if (dateParts.length == 6)
{
dateObj = new Date();
dateObj.setYear(dateParts[0]);
var m = dateParts[1] - 1;
console.log('m= ' + m);
dateObj.setMonth(m);
console.log('after setmonth, date= ' + dateObj);
dateObj.setDate(dateParts[2]);
dateObj.setHours(dateParts[3]);
dateObj.setMinutes(dateParts[4]);
dateObj.setSeconds(dateParts[5]);
}
}
console.log(dateObj);
alert(dateObj);
Your problem, as you figured, is that you're setting the month while the day is still 30. While you could work around that by using setFullYear and pass year, month and day at once, you really should just construct the whole Date object with the right values in the first place:
dateObj = new Date(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]);
or rather using UTC as the timezone:
dateObj = new Date(Date.UTC(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]));
Just figured this out before I submitted. Today is January 30th, 2020. I can't change the month to February, because there is no February 30th. So, the code breaks either on the 29th or the 30th day of the month.
In JavaScript, it is advisable to do
dateObj.setMonth(monthNum -1, dayNum)
to set the day and month at the same time to avoid this problem

Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like:
30 Apr 2015
How do I parse and display the date like this (without Moment.js)?
2015-04-31 (or YYYY-mm-dd)
The easiest thing to do might be to use moment.js.
If you prefer rolling your own solution in vanilla JS, this will work:
var padZero = function (integer) {
return integer < 10 ? '0' + integer : '' + integer
};
var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' +
(padZero(myDate.getMonth()+1)) + '-' +
(padZero(myDate.getDate()));
console.log(myDateString); // 2015-04-30
The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)
var x = new Date("30 Apr 2015");
Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:
console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())
Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).
However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.
Use moment.js
Convert your date like this:
var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30
DEMO
you can do that easy with
//define Date
var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
var months = {
Jan:'01',
Feb:'02',
Mar:'03',
Apr:'04',
May:'05'
};
// split our Date and rearrange as yyyy-mm-dd
var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
alert(reform);// return 2015-04-31

Javascript Displaying Date

I want to display yesterday's date, and day.
Script for today's date:
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
// Array of month Names
var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var now = new Date();
document.write(dayNames[now.getDay()] + ", " +
monthNames[now.getMonth()] + " " +
now.getDate() + ", " + now.getFullYear());
// -->
</script>
I know that adding a -1 will change the date/year, but it doesn't successfully change the day of the week/month because we have listed the days/months in an array, so there is nothing before Sunday and nothing before January.
How can I display the date from yesterday/however days ago making sure the day and month will change?
you can try this: see DEMO
dayNames[now.getDay()==0?6:now.getDay()-1]
EDIT:
and for setDate to yesterday : Demo
now.setDate(now.getDate()-1); // set yesterday for now
You can create a Date instance for yesterday:
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
You can then proceed as you're currently doing things. The JavaScript Date code will ensure that the right thing happens with all the other fields. In other words, if "today" is 1 Jan, then "yesterday" will be 31 Dec of the previous year.
Yesterday's day of the week: dayNames[(now.getDay() + 6) % 7] (equivalent to -1 + 7)
Last month: monthNames[(now.getMonth() + 11) % 12]
Your best bet is to use a sane date handling library and avoid the horrid 70's-style API that JavaScript provides out-of-the-box. Save your time and sanity and use Moment.js:
// this is a quick way to load, not what I would do for production installs:
eval($.get('http://momentjs.com/downloads/moment.min.js').responseText);
document.write(moment().subtract(1, 'day').format("dddd MMMM D, YYYY"));
Note that this means you can subtract things other than days, like months or years, and it works without you having to remember the math (or DST for that matter):
console.log(moment("2008-02-29").subtract(1, 'year').format("dddd MMMM D, YYYY"))
> Wednesday February 28, 2007
console.log(moment("2008-02-29").add(4, 'years').format("dddd MMMM D, YYYY"))
> Wednesday February 29, 2012
console.log(moment("2008-02-29").add(3, 'years').format("dddd MMMM D, YYYY"))
> Monday February 28, 2011

Creating a Javascript Date object by passing in a date? What is a dateString?

I am trying to figure out what the W3C website means by dateString.
http://www.w3schools.com/jsref/jsref_obj_date.asp
I am trying to do something like:
var _date = new Date("Mon Aug 12 2013 2:00 AM");
or even:
var _date = new Date("Mon, Aug 12 2013, 2:00 AM");
Is there a quick way of turning my string into a format that the date object likes?
Thank you
edit:
I suppose it expects the following:
var d = new Date()
d.toDateString()
"Tue Aug 13 2013"
Is it only that type of string?
The Javascript string-based Date constructor accepts strings in a format accepted by Date.parse().
These are date strings compliant with RFC-2822 or ISO-8601.
Use String in this format:
new Date('2013-08-13')
or
new Date('2013-08-13T10:51:00');
Here, this is how to use dateString as a parameter
var dateString = "08/12/2013";
var d = new Date(dateString);
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
Remember month are stored at 0th index in javascript.

Making a basic date(technical)

NO JQUERY! I have a drop down in which the user selects a day month and year. I create the following code and pass these values into the variable using setFullYear. At times I also add days to this variable which is waht the variable ev_num is for. When I write this to the page it displays a lot of unnecessary info...
Sat Jan 01 2011 11:44:26 GMT-0500 (Eastern Standard Time)
I want it to simply read 'Jan 01 2011' or something like that. Does anyone know how I would fix this. Here is a jsfiddle of the entire page... http://jsfiddle.net/fET6v/
var myDate=new Date();
var ev_num = parseInt(document.getElementById("leave").value)
myDate.setFullYear(sel_year.value,sel_month.value,sel_day.value);
var event_value = document.getElementById("leave").value;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
document.write(currentMonth + " " + day + " " + year);
This will print today's date with abbreviated months. It's fully customizable.
http://jsfiddle.net/iansan5653/u7hkE/
EDIT: See this demo for the leading zero in front of the day number: http://jsfiddle.net/iansan5653/u7hkE/1/
If you don't want the time and timezone to appear, use the .toDateString method instead of the simple toString. If you want a custom format, you will need to build the string yourself, you can get the single year/month/date values with the respective methods from your Date object. There are some (googlable) libraries to do that, a single method for your case would be
function myDateString(date) {
return ["Jan","Feb","Mar", …][date.getMonth()] +
" "+("0"+date.getDate()).substr(-2) +
" "+date.getFullYear();
}
http://blog.stevenlevithan.com/archives/date-time-format

Categories

Resources