Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date Object's month index begins with 0

Tags:

My goal is to convert a timestamp from MySQL into a JavaScript Date object in an efficient manner. Here is my current snippet that converts the MySQL timestamp into a formatted date in PHP:

<?php // formats timestamp into following format: 2009, 7, 30 $date =  date("Y, n, j", strtotime($row["date"])); ?> 

I am then using this $date value for a chart using Google's charting API which requires JavaScript Date object:

data.setValue(<?=$count;?>, 0, new Date(<?=$date;?>)); 

The problem is that the JavaScript Date object begins the month index with 0 so the output is always 1 month in advance. What is the most efficient way in dealing with this issue?

Thanks in advance!

like image 987
Allen Liu Avatar asked Jul 30 '09 18:07

Allen Liu


People also ask

Why are months zero indexed in JS?

because they might have an array of string (indexed from 0) of month names and these month numbers if they start from 0, it'll be lot easier to map to the month strings.. Show activity on this post.

How do you get the first date of the month from a date in JavaScript?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now. getFullYear(), now.

What does the getMonth () method of the date object return?

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

How do I +1 a date in JavaScript?

const date = new Date('2022-02-21'); const dateCopy = new Date(date. getTime()); dateCopy. setDate(dateCopy. getDate() + 1); // 👇️ Tue Feb 22 2022 console.


2 Answers

You can feed the Date constructor a date in mm/dd/yyyy or yyyy/mm/dd format and it will convert it:

>>> new Date('7/30/2009'); Thu Jul 30 2009 00:00:00 GMT-0700 (Pacific Daylight Time) >>> new Date('2009/7/30'); Thu Jul 30 2009 00:00:00 GMT-0700 (Pacific Daylight Time) 
like image 173
Paolo Bergantino Avatar answered Dec 28 '22 06:12

Paolo Bergantino


You have to manually subtract that extra 1 from month number I'm afraid. JS Date object is a mess.

like image 30
RaYell Avatar answered Dec 28 '22 06:12

RaYell