Getting the start of the day in a different timezone - javascript

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.

Related

Same date format between MongoDB and JS but they are not equal?

I'm trying to do an action when the date today (via Node.js) and the date value (via MongoDB) is the same. However, I'm not receiving any output from my for loop indicating that there's no match.
Here's how I get the date today (date output is 2023-01-19T00:00:00.000Z):
const d = new Date(new Date().toLocaleString("en-US", { timeZone: "Asia/Hong_Kong" }));
const day = d.getDate();
const month = d.getMonth() + 1;
const year = "2023"; //this is a dummy variable since year is required for Date().
const date = new Date(year + "-" + month + "-" + day);
console.log(date);
Here's the users document from MongoDB:
name: "Angelo"
birthday: 2023-01-11T00:00:00.000+00:00 //Date data type
name: "Josh"
birthday: 2023-01-19T00:00:00.000+00:00 //Date data type
Here's the for loop that should trigger success when there's a match, but there's no output. This is my problem.
let users = [];
db.collection("users").find({})
.forEach((user) => { users.push(user) })
.then(() => {
for (i = 0; i < users.length; i++) {
if(users[i].birthday == date) {
console.log("Success"); //no output on console
}
}
})
Checking users[i].birthday in console shows:
2023-01-19T00:00:00.000Z (Shouldn't this be a match of today's date?)
2023-01-11T00:00:00.000Z
MongoDB Date objects store values in UTC. In your example you create a date object in the local timezone, so your dates will not match.
You can create a UTC zero date using the Date.UTC() static method, where zero date means a date with zero for the hours, minutes, and seconds. Here is an example that simulates your users array from MongoDB, assuming that the birthdays are all UTC zero dates. You can't compare the date objects directly, because two date objects that have the same date have different object addresses. Therefore you need to compare the value of the date objects (.valueOf()), or a string representation (.toISOString()).
function getUtcZeroDate(str) {
if(str) {
return new Date(str + 'T00:00:00.000Z');
} else {
let date = new Date();
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
}
const users = [
{name: 'Angelo', birthday: getUtcZeroDate('2023-01-11') },
{name: 'Josh', birthday: getUtcZeroDate() }, // today
]
const todayUtcZeroDate = getUtcZeroDate();
console.log("Today's UTC zero date:", todayUtcZeroDate.toISOString());
users.forEach(doc => {
const match = (todayUtcZeroDate.valueOf() == doc.birthday.valueOf()) ? 'match' : 'no match';
console.log(doc.name + ', born ' + doc.birthday.toISOString(), '=>', match);
});
Output at the time of writing:
Today's UTC zero date: 2023-01-18T00:00:00.000Z
Angelo, born 2023-01-11T00:00:00.000Z => no match
Josh, born 2023-01-18T00:00:00.000Z => match
A simple way to compare dates is to use setHours(0,0,0) for both birthday date and date like below:
const d = new Date(new Date().toLocaleString("en-US", { timeZone: "Asia/Hong_Kong" }));
const day = d.getDate();
const month = d.getMonth() + 1;
const year = "2023"; //this is a dummy variable since year is required for Date().
let date = new Date(year + "-" + month + "-" + day);
date=date.setHours(0,0,0)
for fetching date and comparing from db:
let users = [];
db.collection("users").find({})
.forEach((user) => { users.push(user) })
.then(() => {
for (i = 0; i < users.length; i++) {
users[i].birthday=new Date(users[i].birthday).setHours(0,0,0)
if(users[i].birthday == date) {
console.log("Success"); // output on console
}
}
})
Try it you will get output.
I suggest considering using moment.js for this.
You'll be also need moment-timezone.js add-on to use timezones.
I recommend moment.js because with it, the code becomes more readable.
moment.tz.setDefault("Asia/Hong_Kong");
const users = [{
name: "Angelo",
birthday: new Date('2023-01-11T00:00:00.000+00:00'),
},
{
name: "Josh",
birthday: new Date('2023-01-19T00:00:00.000+00:00'),
},
];
const today = moment();
for (i = 0; i < users.length; i++) {
const user = users[i];
if ( today.isSame(user.birthday, 'date')) {
console.log("Success", users[i]);
}
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
This is really just a date formatting issue.
If you want to get the date in a particular location, you can use the Intl.DateTimeFormat constructor but get the parts as separate values rather than a timestamp that then must be parsed by the built–in parser. That's a flawed methodology because the built–in parser isn't required to correctly parse such input (same with toLocaleString).
So to get the current date in a particular location and then built a timestamp that is 0hrs UTC:
// Return the date at loc for the provided date as
// a Date set to year, month, day as UTC values.
function toUTCDateFromLoc(loc, date = new Date()) {
let f = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timeZone: loc
});
let {year, month, day} = f.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
return new Date(Date.UTC(year, month - 1, day));
}
// Kirimati and Midway should always be at least 1 day different
['Pacific/Kiritimati', // +14
'Asia/Hong_Kong', // +8
'America/Dominica', // -4
'Pacific/Midway', // -11
].forEach(loc => console.log(
`${loc.padEnd(18, ' ')}: ${toUTCDateFromLoc(loc).toISOString()}`
));

Convert UTC timestamp to other timezone in ISO format

I am trying to convert a UTC timestamp to an ISO-formatted timestamp in German time.
Input: 2022-04-30T17:30:00.000000Z
Expected Output: 2022-04-30T19:30:00
This is my current, working solution but it feels very... hacky... to say the least.
For one, I am afraid that many browsers might not be able to correctly convert the date to the german timezone.
var inputDateString = "2022-04-30T17:30:00.000000Z";
// Convert to German timezone and formatted as iso date
var output = toIsoString(convertTZ(inputDateString, "Europe/Berlin")).split("+")[0];
console.log("inputDateString:", inputDateString)
console.log("output:", output)
// Ref.: https://stackoverflow.com/a/54127122
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", { timeZone: tzString }));
}
// Ref.: https://stackoverflow.com/a/17415677
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? "+" : "-",
pad = function (num) {
return (num < 10 ? "0" : "") + num;
};
return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + "T" + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()) + dif + pad(Math.floor(Math.abs(tzo) / 60)) + ":" + pad(Math.abs(tzo) % 60);
}
Do you know a better/improved solution to this problem that is compatible with most browsers? I feel like JavaScript must offer a better solution for this task without having to rely on external libraries...
Edit:
As an alternative to the toIsoString function, I have also found this: .toLocaleString("sv-SE") but I assume that this has even worse browser support.
If you don't need to guarantee the format of the resulting timestamp, you can use toLocaleDateString plus toLocaleTimeString with a suitable language tag, e.g.
function getISOLocal(loc, date = new Date()) {
return `${date.toLocaleDateString('en-CA', {timeZone: loc})}` +
`T${date.toLocaleTimeString('en', {timeZone: loc, hour12:false})}`;
}
console.log('Current local time in:');
['Pacific/Midway',
'America/New_York',
'Europe/Berlin',
'Pacific/Kiritimati'].forEach(
loc => console.log(`${loc} : ${getISOLocal(loc)}`)
);
But be aware that the format of toLocale* methods is implementation dependent and may vary between implementations, particularly for less common languages and combinations of language, options and host default language.
A better alternative is to use Intl.DateTimeFormat with formatToParts, e.g.
function getISOLocal(loc, date = new Date()) {
let {year, month, day, hour, minute, second} =
new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: loc
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
return `${year}-${month}-${day}T${hour}:${minute}:${second}`
}
console.log('Current local time in:');
['Pacific/Midway',
'America/New_York',
'Europe/Berlin',
'Pacific/Kiritimati'].forEach(
loc => console.log(`${loc} : ${getISOLocal(loc)}`)
);
The timeZone option isn't supported in IE, but maybe that doesn't matter.

How can I get DD-MM-YY hh:mm a, en-US, +0100 format using new Date() [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 1 year ago.
I want time and date format like this
UK: 08-08-21 01:27 PM
SL: 08-08-21 05:57 PM
I tried with this. But i does not work properly
this.subscription = timer(0, 60000)
.pipe(
map(() => new Date()),
share()
)
.subscribe(time => {
let day = new Date().getDay();
let month = new Date().getMonth();
let year = new Date().getFullYear();
let SlHour = new Date().getHours();
let UkHour = new Date().getUTCHours()+ 1;
let minuts = new Date().getUTCMinutes();
let SLTime = day + "-" + month + "-" + year + " " + UkHour + ":" + minuts
let UKTime = day + "-" + month + "-" + year + " " + SlHour + ":" + minuts
}
Can anyone help me to get like this format
UK: 08-08-21 01:27 PM
SL: 08-08-21 05:57 PM
Trying to format the date seperator -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<div>
UK:
<h4 id="app-uk"></h4>
</div>
<div>
SL:
<h4 id="app-sl"></h4>
</div>
<script>
let now = new Date();
let formatDateUK = now.toLocaleString("en-UK", {
dateStyle: "short",
timeStyle: "short",
hour12: true
});
let formatDateSL = now.toLocaleString("en-SL", {
dateStyle: "short",
timeStyle: "short",
hour12: true
});
let displayDateUK = document.querySelector("#app-uk");
displayDateUK.innerHTML = formatDateUK;
let displayDateSL = document.querySelector("#app-sl");
displayDateSL.innerHTML = formatDateSL;
</script>
</body>
</html>
I wrote a formatDate function. If ukTime is true, the result will be London time, and if it is false you will get local time. This should work for your purpose.
The UK time is generated using a date-string-date method because adding 1 to the hour can result in invalid times.
Edit: Fixed 00AM to 12AM.
function formatDate(ukTime = false) {
let dt;
if (ukTime) dt = new Date(new Date().toLocaleString("en-US", { timeZone: "Europe/London" }));
else dt = new Date();
let dayStr = dt.getDate().toString().padStart(2, "0"),
monthStr = (dt.getMonth() + 1).toString().padStart(2, "0"),
yearStr = dt.getYear().toString().substring(1, 3);
let hour = dt.getHours() > 12 ? dt.getHours() - 12 : (dt.getHours() == 0 ? 12 : dt.getHours());
return `${dayStr}-${monthStr}-${yearStr} ${hour.toString().padStart(2, "0")}:${dt.getMinutes().toString().padStart(2, "0")} ${dt.getHours() >= 12 ? "PM" : "AM"}`;
}
console.log(formatDate(true))
console.log(formatDate(false))
There are a number of errors in the code:
let day = new Date().getDay();
returns the day number (Sunday = 0, Monday = 1, etc.) not the date
let month = new Date().getMonth();
returns the month index where Jan = 0, Feb = 1, etc. so you need to add 1 to get the calendar month number.
let UkHour = new Date().getUTCHours()+ 1;
This assumes that the UK time is always UTC +1, which it isn't and also will return 24 when the hour should be 0.
The code also creates a new Date object each time, which is inefficient. To get the date and time in a particular location, use the timeZone option of the Intl.DateTimeFormat constructor, which is also available through toLocaleString.
Since localised formats of dates and times are not standardised, you might use the formatToParts method that returns the parts of a date as an array of objects, where each part has a name and value. Then you can reliably format the parts, e.g. assuming "SL" means "standard local":
// Format date as DD/MM/YY h:mm AP
function formatDate(date = new Date(), location) {
// Standard options
let opts = {
day: '2-digit',
month: '2-digit',
year: '2-digit',
hour: 'numeric',
minute: '2-digit',
second: '2-digit',
hour12: true
};
// Add timezone if supplied
if (location) {
opts.timeZone = location;
}
// Create a formatter
let f = new Intl.DateTimeFormat('en', opts);
// Get the parts
let {year, month, day, hour, minute, dayPeriod} = f.formatToParts(date).reduce(
(acc, part) => {
acc[part.type] = part.value;
return acc
}, {}
);
// Return formatted string
return `${day}-${month}-${year} ${hour}:${minute} ${dayPeriod.toUpperCase()}`;
}
console.log('UK (London): ' + formatDate(new Date(), 'Europe/London'));
console.log('Vladivostok: ' + formatDate(new Date(), 'Asia/Vladivostok'))
console.log('Local : ' + formatDate());
The format DD-MM-YY is ambiguous, not least due to the US penchant for M/D/Y but also because many places use Y-M-D, so 01-02-03 might be interpreted 3 different ways. Better to use the short month name to avoid that, e.g. 09-Aug-21. Four digit year would also be better.

Get the local date instead of UTC

The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)
You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');

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

Categories