JS date and time application scenarios are very broad, such as: comment submission, article publishing, content editing, page monitoring, festival activities and so on, where there is life, there is time.
This is a summary of all the common conversions and all the awesome operations. No longer need to search baidu, just go here (CTRL+C).
Current standard time
First to get the current standard time, parameter for the specified character, position can be arbitrary, pass what have what!
function format(fmt) {
const date = new Date(a)const o = {
"Y+": date.getFullYear(),
"M+": date.getMonth() + 1./ / month
"D+": date.getDate(), / /,
"h+": date.getHours(), / /
"m+": date.getMinutes(), / / points
"s+": date.getSeconds(), / / SEC.
"W": date.getDay() / / week
}
for (var k in o) {
if (new RegExp("("+ k +")").test(fmt)) {
fmt = fmt.replace(RegExp. $1,() = > {
if (k === 'W') { / / week
const week = ['day'.'一'.'二'.'三'.'four'.'five'.'六']
return week[o[k]]
} else if (k === 'Y+' || RegExp.$1.length == 1) { // The year or less than 10 does not add 0
return o[k]
} else {
return ("00"+ o[k]).substr(("" + o[k]).length) // < 10 complement 0}}}})return fmt
}
format('week W') / / Sunday
format("YYYY-MM-DD hh:mm:ss") / / the 2021-03-21 20:24:32
format("MM/DD/YYYY hh:mm") / / the 03-21-2021 May flee
format("MM/DD/YYYY hh:mm") / / the 03-21-2021 May flee
format("YYYY MM: MM :ss week W") // Sunday, 21 March 2021 20:30:14
Copy the code
Expansibility is strong, can be used and modified according to the required structure!
Timestamp conversion
When we store the time field in the database, we usually store it as a timestamp standard.
In front of the display, and how to make it a normal time!
To get the current timestamp, there are three ways:
new Date().getTime() // Accurate to millisecond
new Date().valueOf() // Accurate to millisecond
Date.parse(new Date()) // Accurate to the second
// First get: 1616330071538
Copy the code
We then modify the above method:
function format(fmt, timestamp) {
const date = timestamp ? new Date(timestamp) : new Date(a)/ /...
}
const a = format("YYYY-MM-DD hh:mm:ss")
const b = format("YYYY: MM :ss week W".1616330071538)
// a: 2021-03-21 20:48:30
// B: Sunday 20:34:31, March 21, 2021
Copy the code
To add a timestamp argument, you simply pass the timestamp into the date object.
Long ago
Long ago if we had not met, if no one said those words, then we would still be friends. Accidentally saw our chat records, time stayed in a winter last year, the last message let the phone cold heart!
If you could go to zero like a calculator, would you start again?
const time = (timestemp) = > {
const minute = 1000 * 60;
const hour = minute * 60;
const day = hour * 24;
const month = day * 30;
const year = month * 12;
const diffValue = new Date().getTime() - timestemp; // Current timestamp - Original timestamp = time difference
// If local time is less than variable time
if (diffValue <= 0) {
return 'now'
}
// Calculate the magnitude of difference time
const yearC = diffValue / year;
const monthC = diffValue / month;
const weekC = diffValue / (7 * day);
const dayC = diffValue / day;
const hourC = diffValue / hour;
const minC = diffValue / minute;
// The order from largest to smallest is greater than 1
const map = {
[yearC]: 'years',
[monthC]: "Month",
[weekC]: "Week",
[dayC]: "Day",
[hourC]: "Hour",
[minC]: "Minutes",}for (let i in map) {
if (i >= 1) {
return `The ${parseInt(i)}${map[i]}The former `
}
}
}
time(new Date().getTime() / / now,
time(new Date('2021-1-11').getTime() / / 2 months ago
time(new Date('2021-2-22').getTime() / / 3 weeks ago
time(new Date('2020-3-11').getTime() / / 1 years ago
time(new Date('2019-3-11').getTime() / / 2 years ago
time(new Date(1616330071538).getTime() // 1 hour ago
Copy the code
Most of the moments of friends, comments and articles we see will be displayed in relative time, which requires real-time processing by the front end.
Time range
A common scenario: we buy things on the Internet, there will be a consulting customer service function, of course, customer service also have commuting hours, so how should we judge whether the current time is within the service hours?
For example: Service hours (08:00-20:00) (08:30-20:30)
// The first is simple
function time(beginTime, endTime){
const timeNow = new Date().getHours()
return timeNow >= beginTime && timeNow < endTime
}
time(8.20)
// The second upgrade
function times(beginTime, endTime){
const bDate = beginTime.split(':')
const eDate = endTime.split(':')
const o = {}
const s = ['nDate'.'bDate'.'eDate']
for (let i of s) {
o[i] = new Date(a)let hours, minute;
if (i == 'nDate') {
hours = o[i].getHours()
minute = o[i].getMinutes()
} else {
const arr = i == 'bDate' ? bDate : eDate
hours = arr[0]
minute = arr[1] | |0
}
o[i].setHours(hours)
o[i].setMinutes(minute)
}
// Compare the current, start, and end timestamps, and the answer is clear
return o.nDate.getTime() - o.bDate.getTime() > 0 && o.nDate.getTime() - o.eDate.getTime() < 0
}
// Both are supported
console.log(times('8'.'22'))
console.log(times('at 8:30'.'22:54'))
Copy the code
The emphasis is on the second one, because the judgment operation such as minute and second will be more complicated than just judging the time. The best way is to convert the associated time into time stamps and then calculate them all together! What grade question?
7 days before and after
Increments the previous day’s date to get the specified date array.
// Last 7 days
function getAfterDate(){
let date = new Date().getTime(),
result = [],
newDate,
month,
day;
for (let i = 1; i < 8; i++) {
newDate = date + i * 24 * 60 * 60 * 1000
month = new Date(newDate).getMonth() + 1
day = new Date(newDate).getDate()
result.push(month + The '-' + day)
}
return result
}
/ / [' 3-23 ', '3-24', '3-25', '3-26', '3-27', '3-28', '3-29]
Copy the code
// The first seven days
function getBeforeDate(){
let date = new Date().getTime(),
result = [],
newDate,
month,
day;
for (let i = 7; i > 0; i--) {
newDate = date - i * 24 * 60 * 60 * 1000
month = new Date(newDate).getMonth() + 1
day = new Date(newDate).getDate()
result.push(month + The '-' + day)
}
return result
}
/ / [' 3-15 ', '3-16', '3-17', '3-18', '3-19', '3-20', '3-21]
Copy the code
Whether the date is within seven days
Limit the length of selected dates, such as the date picker in Element-UI, which limits the date to seven days.
/ * * *@param {String} tcimestamp => '2020-05-08 19:46'
*/
function a (timestamp) {
timestamp = new Date(timestamp).getTime()
const endTime = 24 * 60 * 60 * 1000 * 7
const currentTime = new Date().setHours(0.0.0.0)
return currentTime <= timestamp && currentTime + endTime > timestamp
}
console.log(a('2021-3-23')) // true
console.log(a('2021-3-29')) // true
console.log(a('2021-3-30')) // false
Copy the code
- EndTime: Calculates a 7-day timestamp
- CurrentTime: set the currentTime to 0
Then, back to the previous step, customer service to work the calculation!
Invincible and literary, casual collocation
In my personal website, with the following date display way, will be more than the normal time bright spot, and personality fan!
/ * * *@param {String} tcimestamp => '2020-05-08 19:46'
*/
function dateFormat(timestamp) {
const w = new Date(timestamp).getDay() / / for weeks
// Parse time to array
timestamp = timestamp.toString().replace(/-|\:|\/|\ /g.', ').split(', ')
const week = ['day'.'一'.'二'.'三'.'four'.'five'.'六']
const month = ['一'.'二'.'三'.'four'.'five'.'六'.'seven'.'eight'.'九'.'ten'.'十一'.'十二']
const weekEn = ['Sunday'.'Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday'.'Saturday']
const monthEn = ['Jan'.'Feb'.'Mar'.'Apr'.'May'.'Jun'.'Jul'.'Aug'.'Sept'.'Oct'.'Nov'.'Dec']
const opt = ['Y'.'M'.'D'.'h'.'m'.'W'].reduce((t, v, i) = > {
t[v] = v === 'W' ? w : timestamp[i]
return t
}, {})
/ /,
let st = 'st',
nd = 'nd',
rd = 'rd',
th = 'th',
obj = {
1: st,
2: nd,
3: rd,
21: st,
22: nd,
23: rd,
31: st
};
let day = opt.D + (obj[opt.D] ? obj[opt.D] : th)
day = day.startsWith(0)? day.slice(1) : day // remove the preceding 0
const time = {
date: `${opt.Y}/${opt.M}/${opt.D} ${opt.h}:${opt.m}`.time: `${opt.h}:${opt.m}`.year: opt.Y,
month: {
on: opt.M,
cn: month[Number(opt.M) - 1].en: monthEn[Number(opt.M) - 1]},day: {
on: opt.D,
en: day
},
week: {
on: week[opt.W],
en: weekEn[opt.W]
}
}
return time
}
console.log(dateFormat('the 2020-05-08 19:46'))
Copy the code
{
date: '2020/05/30 19:46'.time: '19:46'.year: '2020'.month: { on: '05'.cn: 'five'.en: 'May' },
day: { on: '08'.en: '8th' },
week: { on: 'five'.en: 'Friday'}}Copy the code
With more options, the time you present is more varied and colorful. Show off your unique style!