Javascript Displaying Date - javascript

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

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

MomentJS returns obscure date for 1st of month

I'm having a small problem with MomentJS returning a nonsense date. I am attempting to set the date to the first of a given month and year. I have tried the following:-
var _year = 2015;
var _month = 10;
var _dateString = _year.toString() + '-' + _month.toString() + '-1';
var _date = moment(_dateString, 'YYYY-MM-D');
console.log('_date', _date.format('dddd, do MMMM YYYY'));
This gives Thursday, 4th October 2015 as the _date. Which doesn't exist. I tried using .set() and .date(), both give the same result:-
var _date = moment(_dateString, 'YYYY-MM-D').set('date', 1);
> Thursday, 4th October 2015
var _date = moment(_dateString, 'YYYY-MM-D').date(1);
> Thursday, 4th October 2015
So, I can't see what I'm doing wrong now, can anyone offer any suggestions or help?
Many thanks.
Your code is correct except you should use capital D not small d in do:
console.log('_date', _date.format('dddd, Do MMMM YYYY'));
Difference between Do and do is:
do is the index of the day in the week, for example if you check the calender you will find 1st October is Thursday which is the 4th day of the week as the index start from 0 and if you changed to 2 October which is Friday it will give you 5th and same for 3 Oct => 6th and then the new week start from Sunday then 4 Oct => 0th and start over again.
Do is the index of the day in the month and that what you expected the result to be, 1th Oct is 1th, 2nd Oct => 2nd and so on.
Check the docs here for more info

javascript Today() function

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.

JavaScript Dateobject Increment goes wrong

I want to increment the year-value of a given date, but this goes wrong.
this is my code:
var endDate = entry.start;
endDate.setDate(endDate.getFullYear() + 5);
and for comparison the output (console.log) is:
Date {Thu Jun 30 2011 11:30:10 GMT+0200}
Date {Tue Dec 06 2016 11:30:10 GMT+0100}
as you can see, it also incremented the month and Day.
What am I missing?
thanks in advance
You have to set the year only, using the setYear method:
endDate.setYear(endDate.getFullYear() + 5);
Using setDate(getFullYear()+5) you add 5 + (year of the date) days to the date value of endDate
You're adding 2016 days to it, not modifying the year, which is 5 and a half year.

jquery, work with date

how in jQuery work date?
I want to perform mathematical operations to date.
var date = '2010-11-23 21:32:31';
var date = date - 70;
alert(date);
how get:
2010-11-23 21:31:21
Thanks
Try:
http://www.datejs.com/
It's not jQuery, but will solve your problems.
From their sample page:
// What date is next thrusday?
Date.today().next().thursday();
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
// 6 months from now
var n = 6;
n.months().fromNow();
// Set to 8:30 AM on the 15th day of the month
Date.today().set({ day: 15, hour: 8, minute: 30 });
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
This is not really a jQuery question as it is more a javascript question. For that answer, have a look at this: http://www.w3schools.com/jsref/jsref_obj_date.asp.

Categories

Resources