How to get year/month/day from a date object? - javascript

alert(dateObj) gives Wed Dec 30 2009 00:00:00 GMT+0800
How to get date in format 2009/12/30?

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
or you can set new date and give the above values

new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"

var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
Since month index are 0 based you have to increment it by 1.
Edit
For a complete list of date object functions see
Date
getMonth()
Returns the month (0-11) in the specified date according to local time.
getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.

Why not using the method toISOString() with slice or simply toLocaleDateString()?
Beware that the timezone returned by toISOString is always zero UTC offset, whereas in toLocaleDateString it is the user agent's timezone.
Check here:
const d = new Date() // today, now
// Timezone zero UTC offset
console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD
// Timezone of User Agent
console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD
console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY

I would suggest you to use Moment.js http://momentjs.com/
Then you can do:
moment(new Date()).format("YYYY/MM/DD");
Note: you don't actualy need to add new Date() if you want the current TimeDate, I only added it as a reference that you can pass a date object to it. for the current TimeDate this also works:
moment().format("YYYY/MM/DD");

2021 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
new Date().toLocaleDateString() // 8/19/2020
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 09 (just the hour)
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.

var date = new Date().toLocaleDateString()
"12/30/2009"

info
If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)
code
var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);
output
2016/10/06
fiddle
https://jsfiddle.net/Hastig/1xuu7z7h/
credit
More info from and credit to this answer
more
To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.

let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
For reference you can see the below details
new Date().getDate() // Return the day as a number (1-31)
new Date().getDay() // Return the weekday as a number (0-6)
new Date().getFullYear() // Return the four digit year (yyyy)
new Date().getHours() // Return the hour (0-23)
new Date().getMilliseconds() // Return the milliseconds (0-999)
new Date().getMinutes() // Return the minutes (0-59)
new Date().getMonth() // Return the month (0-11)
new Date().getSeconds() // Return the seconds (0-59)
new Date().getTime() // Return the time (milliseconds since January 1, 1970)
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
console.log(myDate)

Use the Date get methods.
http://www.tizag.com/javascriptT/javascriptdate.php
http://www.htmlgoodies.com/beyond/javascript/article.php/3470841
var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();

Nice formatting add-in: http://blog.stevenlevithan.com/archives/date-time-format.
With that you could write:
var now = new Date();
now.format("yyyy/mm/dd");

EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.
function getFormattedDate(today)
{
var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var day = week[today.getDay()];
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hour = today.getHours();
var minu = today.getMinutes();
if(dd<10) { dd='0'+dd }
if(mm<10) { mm='0'+mm }
if(minu<10){ minu='0'+minu }
return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}
var date = new Date();
var text = getFormattedDate(date);
*For Spanish format, just translate the WEEK variable.
var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
Output: Monday - 16/11/2015 14:24

With the accepted answer, January 1st would be displayed like this: 2017/1/1.
If you prefer 2017/01/01, you can use:
var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();

Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
console.log(formattedDate);

It's Dynamic It will collect the language from user's browser setting
Use minutes and hour property in the option object to work with them..
You can use long value to represent month like Augest 23 etc...
function getDate(){
const now = new Date()
const option = {
day: 'numeric',
month: 'numeric',
year: 'numeric'
}
const local = navigator.language
labelDate.textContent = `${new
Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()

You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();

ES2018 introduced regex capture groups which you can use to catch day, month and year:
const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);
Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.
Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/

One liner, using destructuring.
Makes 3 variables of type string:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')
Makes 3 variables of type number (integer):
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))
From then, it's easy to combine them any way you like:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;

I am using this which works if you pass it a date obj or js timestamp:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}

Related

I calculated to get the first day of the month but go the last

I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31 as the first day instead of 2019-06-01?
You could use a simple regex to format the string using replace:
/(\d{4})-(\d{2})-(\d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(\d{4})-(\d{2})-(\d{2}).+/, '$3-$2-$1')
console.log(formatted)
The default javascript date uses your local timezone, by converting it to something else you can end up with a different date.
You can do it
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
The date object in javascript can be somewhat tricky. When you create a date, it is created in your local timezone, but toISOString() gets the date according to UTC. The following should convert the date to ISO but keep it in your own time zone.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);

How do I get the date to print only the day of the week?

How do i print only the date of the week with JS. Or maybe the day and month?
I was playing around with some functions but I only get the whole date.
let today = new Date()
today.getDate()
let tomorrow = new Date();
tomorrow.getDay(today.getDate()+1)
Then I will have to use the variable as props in a react component and it should be a string.
So should I use toUTCstring?
You can use the weekday option of toLocaleString:
mydateobject.toLocaleString("en", { weekday: "long" })
The month name can be got in a similar way:
mydateobject.toLocaleString("en", { month: "long" })
getDay takes no arguments. You're looking for setDate to set the date to tomorrow, and then use getDay without arguments:
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
let days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
console.log('tomorrow is: ' + days[tomorrow.getDay()])
You can use the getDay() method. This will return a number. You can use this number to get the name of the day. Something like this
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
let date = new Date();
var day_of_week = date.getDay();
var day_name = days[day_of_week];
the javascript Date object has many methods to get what you want: you can use getDay() to get the day of the week and getMonth() to get the month.
To pass this as a string parameter I believe the best would be to use toISOString() and you can use this string as a parameter to the Date constructor on the other side.
For handling dates I recommend using moment js library
you can install it with npm install moment and then
moment().format('E');
or
moment().utc.().format('E');
or just moment().day()
Looks like toDateString will always return the 3 letters of the day if the week, so you can:
// Today
new Date().toDateString().substring(0,3)
// Tomorrow
new Date(Date.now()+24*3600*1e3).toDateString().substring(0,3)
Or, to get the number (zero based):
// Today
new Date().getDay()
// Tomorrow
new Date(Date.now()+24*3600*1e3).getDay()
If you use momentjs library, you can use let day = moment(tomorrow).format('dddd');
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow)
let day = moment(tomorrow).format('dddd');
console.log(day);
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow)
let day = moment(tomorrow).format('dddd');
console.log(day);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Using Date.toDateString() you can format into dd mmm yy (or any way you want):
let date = new Date
str = date.toDateString() // 'Mon May 06 2019
let arr = str.split(" ") // ['Mon', 'May', '06', '2019']
let formatted = parseInt(arr[2]).toString() + " " + arr[1] + " " + arr[3] //6 May 2019
console.log(formatted) //6 May 2019
Using Date.toLocaleString() gives weekday:
let date = new Date
let weekdayLong = date.toLocaleString('en-gb', {weekday: 'long'}) //Monday
let weekdayShort = date.toLocaleString('en-gb', {weekday: 'short'}) //Mon

Javascript get start of the month

How to get the start of the month in date format e.g. 01-05-2017?
I have already seen
Get first and last date of current month with javascript or jquery
If I understand correctly toLocaleString() might do what you want.
For example:
lastDay.toLocaleString('en-GB', {day: 'numeric', month: '2-digit', year: 'numeric'});
For more info (MDN)
Replace locale with any that suits your desired formatting.
After getting the date we need to convert it to desired string format.
01 is the day and may be a constant since every beginning of the month starts from 1.
getMonth returns number of the month starting from 0 so we need a little function to format it.
var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth(), 1);
var startDateString = '01-' + fotmatMonth(startDate.getMonth()) + '-' + startDate.getFullYear();
console.log(startDateString);
function fotmatMonth(month) {
month++;
return month < 10 ? '0' + month : month;
}
var date = new Date();
console.log(getStartOfMonthDateAsString(date));
function getStartOfMonthDateAsString() {
function zerosPad(number, numOfZeros) {
var zero = numOfZeros - number.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + number;
}
var day = zerosPad(1, 2);
var month = zerosPad((date.getMonth() + 1), 2);
var year = date.getFullYear();
return day + '-' + month + '-' + year;
}

How to convert timestamp to readable date/time?

I have an API result giving out timestamp like this 1447804800000. How do I convert this to a readable format using Javascript/jQuery?
You can convert this to a readable date using new Date() method
if you have a specific date stamp, you can get the corresponding date time format by the following method
var date = new Date(timeStamp);
in your case
var date = new Date(1447804800000);
this will return
Wed Nov 18 2015 05:30:00 GMT+0530 (India Standard Time)
Call This function and pass your date :
JS :
function getDateFormat(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
var date = new Date();
date.toLocaleDateString();
return [day, month, year].join('-');
}
;
In my case, the REST API returned timestamp with decimal. Below code snippet example worked for me.
var ts= 1551246342.000100; // say this is the format for decimal timestamp.
var dt = new Date(ts * 1000);
alert(dt.toLocaleString()); // 2/27/2019, 12:45:42 AM this for displayed

A twofold javascript function to convert a long date and return today's date in mm-dd-yyyy format

I need your help,
I can't seem to find any other help on this on the internet, because it seems its either one way ot the other. What I would like to be able to do is to create a combined, two-fold javascript function that would convert a long date string into the mm-dd-yyyy format, and when the same function is called again with no string specified to convert, to just return todays date in mm-dd-yyyy format.
Example:
getDate(Fri May 22 2015 13:32:25 GMT-0400)
would return: 05-22-2015
getDate()
would return today's date of 05-23-2015
Hi this should do the trick
FORMAT: mm-dd-yyyy
function addZeroIfRequired(dayOrMonth) {
return dayOrMonth > 9 ? dayOrMonth : "0"+dayOrMonth;
}
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return addZeroIfRequired((date.getUTCMonth()+1)) + "-" +
addZeroIfRequired(date.getDate())+ "-" +
date.getUTCFullYear();
}
console.log(getDate()); // 05-23-2015
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400")); 05-22-2015
NOTE: the +1 after the getUTCMonth().
JSFiddle. Open the console to see the result. https://jsfiddle.net/wt79yLo0/2/
ISO FORMAT: yyyy-mm-dd
Just in case someone is interested in the opposite format, the code would be much nicer and neater:
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return date.toISOString().substring(0, 10);
}
console.log(getDate());
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400"));
https://jsfiddle.net/wt79yLo0/
First I would recommend a very powerful library for JS called Moment.js which solves all this kind of problems.
But if you only want a snippet, here is my proposal:
function twoDigits(num) {
return ("0" + num).substr(-2);
}
function getFormattedDateDMY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [day,month,year].join(separator);
}
function getFormattedDateMDY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [month,day,year].join(separator);
}
console.log(getFormattedDateDMY(new Date(), "-")); //23-04-2015
console.log(getFormattedDateMDY(new Date(), "-")); //04-23-2015
With getDate(), getMonth() and getFullYear(). You have to set a "0" before the months and days which are < 10. GetMonth() starts with 0, therefore (getMonth() + 1).
function getFormattedDate() {
var date = new Date();
var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
var year = date.getFullYear();
var formattedDate = day + "-" + month + "-" + year;
return formattedDate;
}
console.log(getFormattedDate());
Demo

Categories