Get hours, minutes and seconds, ... from Unix epoch at UTC [duplicate] - javascript

My brain must be utterly fried, but I cannot for the life of me figure out how to get the current date and time in UTC formatted as a string. No matter what I do, I just get local.
I have the following function which returns the date in the correct format, but it's always local.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
Does anyone know what I'm missing?

We should use in-built toISOString function to covert it to ISO date format and remove not required data using string manipulation.
let datenow = new Date();
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
return date.toISOString().replace("T"," ").substring(0, 19);
}
Ideally solution should be to use momentjs or dayjs library.

A simple way can be getting each UTC unit from the new Date() object and creating the desired string.
const date = new Date();
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // Month is 0-based
const day = String(date.getUTCDate()).padStart(2, '0');
const hour = String(date.getUTCHours()).padStart(2, '0');
const minute = String(date.getUTCMinutes()).padStart(2, '0');
const second = String(date.getUTCSeconds()).padStart(2, '0');
const strDate = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
console.log(strDate);
Adding a valuable suggestion by RobG, as sometimes comments get deleted:
Somewhat simpler: new Date().toLocaleString('en-CA',{timeZone:'UTC', hour12:false}).replace(',','').

Adding this answer as well that RobG suggested.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false,
timeZone:'UTC'
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}

Related

Javascript Date Now (UTC) in yyyy-mm-dd HH:mm:ss format

My brain must be utterly fried, but I cannot for the life of me figure out how to get the current date and time in UTC formatted as a string. No matter what I do, I just get local.
I have the following function which returns the date in the correct format, but it's always local.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
Does anyone know what I'm missing?
We should use in-built toISOString function to covert it to ISO date format and remove not required data using string manipulation.
let datenow = new Date();
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
return date.toISOString().replace("T"," ").substring(0, 19);
}
Ideally solution should be to use momentjs or dayjs library.
A simple way can be getting each UTC unit from the new Date() object and creating the desired string.
const date = new Date();
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // Month is 0-based
const day = String(date.getUTCDate()).padStart(2, '0');
const hour = String(date.getUTCHours()).padStart(2, '0');
const minute = String(date.getUTCMinutes()).padStart(2, '0');
const second = String(date.getUTCSeconds()).padStart(2, '0');
const strDate = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
console.log(strDate);
Adding a valuable suggestion by RobG, as sometimes comments get deleted:
Somewhat simpler: new Date().toLocaleString('en-CA',{timeZone:'UTC', hour12:false}).replace(',','').
Adding this answer as well that RobG suggested.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false,
timeZone:'UTC'
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}

How to check if date is today or yetsterday or return date? [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
How can i check if input date is Today, Yesterday or just return the date if it's noone of them?
I was trying to do the following:
const checkDate = (someDate) => {
const today = new Date();
let date = new Date(someDate);
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return date.getTime() === today.getTime() ? "Oggi" : date.getTime() === today.setDay(-1) ? "Ieri" : "Il" + date;
}
console.log(checkDate("December 17, 1995 03:24:00"));
Where "Oggi" is Today and "Ieri" is Yesterday..
The easiest and most probably the right way is to use some library. Try day.js - small, but features rich (similar to Moment).
To install:
npm install dayjs
Or CDN:
<script src="https://unpkg.com/dayjs#1.8.21/dayjs.min.js"></script>
And you are ready to use all the set of features:
const someDate = new Date(); // plain old JS date
const now = dayjs(); // same (current date) but with day.js
// of course you can do: dayjs(someDate)
// yesterday: you check if someDate is current date - 1 day
const isYesterday = dayjs(someDate).isSame(dayjs().subtract(1, 'day'))
// today: just check if some date is equal to current date
const isToday = dayjs(someDate).isSame(dayjs()); // dayjs() return current date
// want to get back to plain old JS date
conat plainOldJsDate = dayjs('2019-01-25').toDate();
You can find more awesome features like parsing, manipulating, formatting, etc. in official docs.
isToday:
const isToday = (date) => {
const today = new Date()
return date.getDate() === today.getDate() &&
date.getMonth() === today.getMonth() &&
date.getFullYear() === today.getFullYear();
};
isYesterday:
const isYesterday = (date) => {
var yesterday= new Date();
yesterday; //# => today
date.setDate(date.getDate() - 1);
yesterday; //# => yesterday
return date.getDate() === yesterday.getDate() &&
date.getMonth() === yesterday.getMonth() &&
date.getFullYear() === yesterday.getFullYear();
}
The issue was that i missed to set mills and setDay was invalid, solved by using setDate(getDate() - 1) and by setting mills to 0
Here is the final solution
const checkDate = (someDate) => {
let today = new Date();
let date = new Date(someDate);
date = resetHours(date);
today = resetHours(today);
return date.getTime() === today.getTime() ? "Oggi" : date.getTime() === today.setDate(today.getDate() - 1) ? "Ieri" : "Il" + date;
}
const resetHours = (date) => {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
You need to get the current date with a Date() object, then compare.
The function receives strings in the form of mm/dd/yyyy.
function checkDate(date) {
// get today
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
// parse into strings
today = mm + '/' + dd + '/' + yyyy;
yesterday = mm + '/' + (dd-1) + '/' + yyyy;
if (today == date) {
return 'today';
}
if (today == yesterday) {
return 'yesterday';
}
else {
return date;
}
}
var date = '01/04/2021';
console.log(checkDate(date));
Compare .toDateString to check if a Date() is the same day:
const checkDate = (someDate) => {
// Create 'today' Date object
const today = new Date();
// Create 'someDate' Date object
const date = new Date(someDate);
// is Today
if (date.toDateString() === today.toDateString()) {
return 'today';
}
// Alter date to yesterday
today.setDate(today.getDate() - 1);
// is Yesterday
if (date.toDateString() === today.toDateString()) {
return 'yesterday';
}
// Fallback
return 'fallback'
}
console.log(checkDate('1/4/2021')); // today
console.log(checkDate('1/3/2021')); // yesterday
console.log(checkDate('1/9/2021')); // fallback
const isSameDay = (a, b) => {
return a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate()=== b.getDate();
}
const checkDate = (date) => {
const today = new Date();
const yesterday = new Date(Date.now() - 86400000); // 24 * 60 * 60 * 1000
if (isSameDay(today, date)) {
return "Today";
} else if (isSameDay(yesterday, date)) {
return "Yesterday";
} else {
return date.toDateString();
}
}
console.log(checkDate(new Date())); // "Today"
console.log(checkDate(new Date(Date.now() - 86400000))); // "Yesterday"
console.log(checkDate(new Date(Date.now() - 86400000 * 3))); // "Fri Jan 01 2021"
Date documentation in MDN

Getting the start of the day in a different timezone

I have a Date. It is in the local timezone. I want a new Date that is at the beginning of the dayin a different timezone. Here are some things I do not want:
A Date in UTC equivalent to the first date converted to UTC
A string
Specifically, UTC does not work because getting the start of a day in UTC is not the same as getting the start of the day in a timezone.
So If I have a date in Calcutta and want to get the start of that day in San Francisco, the date in Calcutta and the date in Greenwich might not be the same date. It could be June 15th in Calcutta, June 15th in Greenwich, but June 2nd in San Francisco. So calling setMinutes(0) etc on a date that is set to UTC will not work.
I am also using date-fns (not moment) if that's helpful, but it doesn't seem to be because all dates (including those in date-fns-tz) are returned in either local or UTC time.)
Is this possible in Javascript or am I insane?
Note:
This is not the same as Convert date to another timezone in JavaScript
That is about converting to strings. I do not want strings.
One way is to:
Get the current timezone offset at the required location
Create a date for the required UTC date
Apply the offset from #1
e.g. using the answer at Get Offset of the other Location in Javascript:
function getTimezoneOffset(date, loc) {
let offset;
['en','fr'].some(lang => {
let parts = new Intl.DateTimeFormat(lang, {
minute: 'numeric',
timeZone: loc,
timeZoneName:'short'
}).formatToParts(date);
let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
if (/^(GMT|UTC)/.test(tzName[0].value)) {
offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
return true;
}
});
let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
let [h, m] = offset.substring(1).split(':');
return sign + h.padStart(2, '0') + ':' + (m || '00');
}
// Convert offset string in ±HH:mm to minutes
function offsetToMins(offset) {
let sign = /^-/.test(offset)? -1 : 1;
let [h, m] = offset.match(/\d\d/g);
return sign * (h * 60 + Number(m));
}
// Format date as YYYY-MM-DD at loc
function formatYMD(loc, date) {
let z = n => ('0'+n).slice(-2);
let {year, month, day} = new Intl.DateTimeFormat('en',{timeZone: loc})
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return part;
}, Object.create(null));
return `${year}-${z(month)}-${z(day)}`
}
// Return stat of day for date at loc
function startOfDayAtLoc(loc, date = new Date()) {
let offset = getTimezoneOffset(date, loc);
let offMins = offsetToMins(offset);
let d = new Date(+date);
d.setUTCHours(0, -offMins, 0, 0);
// If date is + or - original date, adjust
let oDateTS = formatYMD(loc, date);
let sodDateTS = formatYMD(loc, d);
if (sodDateTS > oDateTS) {
d.setUTCDate(d.getUTCDate() - 1);
} else if (sodDateTS < oDateTS) {
d.setUTCDate(d.getUTCDate() + 1);
}
return d;
}
// QnD formatter
let f = (loc, d) => d.toLocaleString('en-gb', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour12:false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: loc,
timeZoneName: 'long'
});
// Examples
// 1 June 2020 00:00:00 Z
let d = new Date(Date.UTC(2020, 5, 1));
['America/New_York',
'Asia/Tokyo',
'Pacific/Tongatapu',
'Pacific/Rarotonga'
].forEach(loc => {
let locD = startOfDayAtLoc(loc, d);
console.log(loc + ' ' + getTimezoneOffset(d, loc) +
'\nZulu : ' + locD.toISOString() +
'\nLocal: ' + f(loc, locD));
});
// Dates on different date to UTC date
let laDate = new Date('2022-04-30T18:00:00-07:00');
let la = 'America/Los_Angeles';
console.log(`${la} - ${f(la, laDate)}` +
`\nStart of day: ${f(la, startOfDayAtLoc(la, laDate))}`
);
let chaDate = new Date('2022-05-01T03:00:00+10:00');
let cha = 'Pacific/Chatham';
console.log(`${cha} - ${f(cha, chaDate)}` +
`\nStart of day: ${f(cha, startOfDayAtLoc(cha, chaDate))}`
);
However, I'd suggest you use a library with timezone support as there are many quirks with the Date object and there is a new Temporal object in the works.

Timestamp to human readable format

Well I have a strange problem while convert from unix timestamp to human representation using javascript
Here is timestamp
1301090400
This is my javascript
var date = new Date(timestamp * 1000);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hour = date.getHours();
var minute = date.getMinutes();
var seconds = date.getSeconds();
I expected results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0
What I miss ?
getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth() + 1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())
const timestamp = 1301090400;
const date = new Date(timestamp * 1000);
const datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
Here is a small helper idea to retrieve values of a given Date:
const dateHelper = dateHelperFactory();
const formatMe = date => {
const vals = `yyyy,mm,dd,hh,mmi,ss,mms`.split(`,`);
const myDate = dateHelper(date).toArr(...vals);
return `${myDate.slice(0, 3).join(`/`)} ${
myDate.slice(3, 6).join(`:`)}.${
myDate.slice(-1)[0]}`;
};
// to a formatted date with zero padded values
console.log(formatMe(new Date(1301090400 * 1000)));
// the raw values
console.log(dateHelper(new Date(1301090400 * 1000)).values);
function dateHelperFactory() {
const padZero = (val, len = 2) => `${val}`.padStart(len, `0`);
const setValues = date => {
let vals = {
yyyy: date.getFullYear(),
m: date.getMonth()+1,
d: date.getDate(),
h: date.getHours(),
mi: date.getMinutes(),
s: date.getSeconds(),
ms: date.getMilliseconds(), };
Object.keys(vals).filter(k => k !== `yyyy`).forEach(k =>
vals[k[0]+k] = padZero(vals[k], k === `ms` && 3 || 2) );
return vals;
};
return date => ( {
values: setValues(date),
toArr(...items) { return items.map(i => this.values[i]); },
} );
}
.as-console-wrapper {
max-height: 100% !important;
}
Or see this small stackblitz project (a little bit more efficient).
var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();
Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.
For example, using it for the current time:
document.write( new Date().toUTCString() );
here is kooilnc's answer w/ padded 0's
function getFormattedDate() {
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
month = (month < 10 ? "0" : "") + month;
day = (day < 10 ? "0" : "") + day;
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
sec = (sec < 10 ? "0" : "") + sec;
var str = date.getFullYear() + "-" + month + "-" + day + "_" + hour + ":" + min + ":" + sec;
/*alert(str);*/
return str;
}
use Date.prototype.toLocaleTimeString() as documented here
please note the locale example en-US in the url.
I was looking for a very specific solution for returning the current time as a guaranteed length string to prepend at the beginning of every log line. Here they are if someone else is looking for the same thing.
Basic Timestamp
"2021-05-26 06:46:33"
The following function returns a zero padded timestamp for the current time (always 19 characters long)
function getTimestamp () {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date();
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
Full Timestamp
"2021-06-02 07:08:19.041"
The following function returns a zero padded timestamp for the current time including milliseconds (always 23 characters long)
function getFullTimestamp () {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date();
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(),3)}`;
}
Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:
var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)
To direct get a readable local timezone:
var timestamp = 1301090400,
date = new Date(timestamp * 1000)
document.write( date.toLocaleString() );
I'm too late to the party since this question is already a decade old, but I want to provide a cleaner one without the use of any plugins like moment.js. only vanilla javascript.
export default {
// Accepts "1998-08-06 11:00:00" <-- This is UTC timestamp
getFormalDateTime(utcDate) {
const formattedUtc = utcDate.split(' ').join('T')+'Z'
let date = new Date(formattedUtc);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
let timeString = date.toLocaleTimeString("en-US", {hour: 'numeric', minute: 'numeric', hour12: true});
let formattedDate = dateString + " | " + timeString;
return formattedDate; // Returns "August 6, 1998 | 11:00 AM" <-- This is converted to client time zone.
},
// Accepts: "1998-08-06"
getFormalDate(convertDate) {
let date = new Date(convertDate);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
return dateString // Returns "August 6, 1998"
}
}
My code is formatted for ES6 modules because I use it as a module for my vuejs project but you can convert it to a normal javascript function.
getFormalDateTime('1998-08-06 11:00:00') the parameter should be in UTC time. This will return a formal date time converted to the client/browser timezone: August 6, 1998 | 11:00 AM
getFormalDate('1998-08-06') will just return August 6, 1998
More information here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

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

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);
}
}

Categories