코딩

javascript 도구 디자인 : 시계 clock

Jonah's Whale 2019. 1. 27. 21:31


리얼타임 시간


const clockBox = document.querySelector(".clockOfh1");

function getTime(){
const date = new Date;
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
clockBox.innerText =
`${hours < 10 ? `0${hours}` : hours }:${
minutes < 10 ? `0${minutes}` : minutes }:${
seconds < 10 ? `0${seconds}` : seconds }`;
}



function init(){
getTime();
setInterval(getTime, 1000);
}
init();




몽고 db에서 데이터를 가져와서 시간을 붙이는 것



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// models/post.js
const mongoose = require("mongoose")
//schema
const postSchema = mongoose.Schema({
    title:{type:String, required:true},
    body:{type:String},
    createAt:{type:Datedefault:Date.now},
    updateAt:{type:Date},
},{toObject:{virtuals:true}});
//virtuals
postSchema.virtual("createdDate")
.get(()=>{
    return getDate(this.createAt)
});
postSchema.virtual("createdTime")
.get(()=>{
    return getTime(this.createdAt)
});
postSchema.virtual("updatedDate")
.get(()=>{
    return getDate(this.updateAt)
});
postSchema.virtual("updatedTime")
.get(()=>;{
    return getTime(this.updatedAt)
});
//model 
const Post = mongoose.model("post",postSchema);
//export
module.exports = Post;
//functions... 숫자를 지정 
function getDate(dateObj){
    if(dateObj instanceof Date)//대략해석, Date라는 객체 안에 dateObj라는 객체가 있다.
    return dateObj.getFullYear() + "-" + get2digits(dateObj.getMonth()+1+ "-" + get2digits(dateObj.getDate());
};
function getTime(dateObj){
    if(dateObj instanceof Date)
    return get2digits(dateObj.getHours()) + ":" + get2digits(dateObj.getMinutes()) + ":" + get2digits(dateObj.getSeconds());
};
function get2digits(num){ //이 함수는 단순히 get2digits에다가 ("0"+인자).slice(-2)를 붙여주기 위함이다
    return ("0"+num).slice(-2)
}
cs


설명

https://stackoverflow.com/Questions/3605214/javascript-add-leading-zeroes-to-date


https://stackoverflow.com/questions/6040515/how-do-i-get-month-and-date-of-javascript-in-2-digit-format




('0' + (MyDate.getMonth()+1)).slice(-2) 

여기서 +1을 하는 이유는 

0부터 시작하기 때문이다..

1월이 0이고  12월이 11이기 때문이다