Các hàm thường dùng
Hàm tính thời gian đã qua
const calculateElapsedTime = (timeCreated) => {
const created = new Date(timeCreated).getTime();
let periods = {
year: 365 * 30 * 24 * 60 * 60 * 1000,
month: 30 * 24 * 60 * 60 * 1000,
week: 7 * 24 * 60 * 60 * 1000,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
};
let diff = Date.now() - created;
for (const key in periods) {
if (diff >= periods[key]) {
let result = Math.floor(diff / periods[key]);
return `${result} ${(result === 1 ? key : key + "s")} ago`;
}
}
return "Just now";
};
calculateElapsedTime("2022-05-20T09:03:20.229Z")
// output: 2 minutes ago
Sao chép ảnh
const copyImageToClipboard = async (imageElement) => {
let canvas = document.createElement("canvas");
canvas.width = imageElement.width;
canvas.height = imageElement.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(imageElement, 0, 0);
const dataURL = canvas.toDataURL();
const blob = await (await fetch(dataURL)).blob();
navigator.clipboard.write([
new ClipboardItem({
"image/png": blob,
}),
]);
};
Sao chép văn bản
const copyToClipboard = (text) => {
try {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text);
} else {
let textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
document.execCommand("copy") ? res() : rej();
textArea.remove();
});
}
} catch (error) {
console.error(error);
}
};
Force download file
const forceDownloadFile = (url) => {
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = url;
anchor.style.display = "none";
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
};