ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 항해 99 5기 TIL_78
    항해 99 2022. 3. 29. 02:38

    ▶ Today I Learned

     

    <실전 프로젝트>

     

    [주가 바뀔 때 시간 초기화]

     

    아래와 같은 코드를 짰다.

    let oneDay = 86400000
    
    let lastUpdateDate = new Date(2021,2,20,0)
    let checkingDate = new Date(2021,2,27,1) // 확인 날짜
    
    console.log(checkingDate.getDay(), "checkingDate.getDay()")
    console.log(lastUpdateDate.getDay(),"lastUpdateDate.getDay()")
    
    
    let lastUpdatedZeroHour = new Date(lastUpdateDate.getFullYear(), lastUpdateDate.getMonth(), lastUpdateDate.getDate(), 0)
    
    let checkingZeroHour = new Date(checkingDate.getFullYear(), checkingDate.getMonth(), checkingDate.getDate(), 0)
    
    console.log(lastUpdatedZeroHour.getDay(),"lastUpdatedZeroHour.getDay()")
    console.log(checkingZeroHour.getDay(),"checkingZeroHour.getDay()")
    
    // console.log(new Date(2022,2,27,0.5).getTime(), "이전꺼")
    // console.log(lastUpdatedZeroHour.getTime(), "오오 lastUpdatedZeroHour")
    // console.log(checkingZeroHour.getTime(), "checkingZeroHour - 7 * oneDay")
    
    // 요일초기화 기준
    
      
    if (checkingZeroHour.getDay() === 0) {
    
      console.log(lastUpdatedZeroHour <= checkingZeroHour - 7 * oneDay? true : false, "111")
            console.log(checkingZeroHour + 1 * oneDay <= lastUpdatedZeroHour? true : false, "222")
      if ( lastUpdatedZeroHour <= checkingZeroHour - 7*oneDay || checkingZeroHour + 1*oneDay <= lastUpdatedZeroHour) {
    
        // 요일 초기화 실행
        console.log("초기화 가즈아")
        console.log("일요일") 
      }
    } 
    // else {
    //   if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) 
    else if (checkingZeroHour.getDay() === 1)
      {
        if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) {
    
    console.log("월요일")
          
        }
      } else if (checkingZeroHour.getDay() === 2)
      {
        if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) {
    
    console.log("화요일")
          
        } 
    
        // 요일 초기화 실행
        console.log("초기화 가즈아2")
      } else if (checkingZeroHour.getDay() === 3)
      {
        if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) {
    
    console.log("수요일")
          
        } 
    
        // 요일 초기화 실행
        console.log("초기화 가즈아2")
      } else if (checkingZeroHour.getDay() === 4)
      {
        if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) {
    
    console.log("목요일")
          
        } 
    
        // 요일 초기화 실행
        console.log("초기화 가즈아2")
      } else if (checkingZeroHour.getDay() === 5)
      {
        if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) {
    
    console.log("금요일")
          
        } 
    
        // 요일 초기화 실행
        console.log("초기화 가즈아2")
      } else if (checkingZeroHour.getDay() === 6)
      {
        if ( lastUpdatedZeroHour <= checkingZeroHour - checkingZeroHour.getDay()*oneDay || checkingZeroHour + (8-checkingZeroHour.getDay())*oneDay <= lastUpdatedZeroHour) {
    
    console.log("토요일")
          
        } 
    
        // 요일 초기화 실행
        console.log("초기화 가즈아2")
      }

     

    이렇게 했더니 그 콘솔 결과는 다음과 같았다.

     

    6 checkingDate.getDay()
    6 lastUpdateDate.getDay()
    6 lastUpdatedZeroHour.getDay()
    6 checkingZeroHour.getDay()
    토요일
    초기화 가즈아2

     

    분명 일요일인데 이유를 확인해보니..

    "The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday. "

    즉, getDay()는 로컬 시간을 기준으로 요일을 보여주는 것이었다.

    replit이나 aws ec2의 경우 로컬 시간의 기준이 북미이므로 내 화면상에 한국 시간을 2022.3.27이라고 띄워도 일요일이 아닌 토요일로 인식해버리는 것이다.

     

    라고 생각했는데??

     

    브라우저에서 돌려도 같은 결과가 나왔다..

    ??????

    아 .. 그런데 다시보니 2022년이 아니라 2021을 기준으로 보고있었다...

    역시.. 코딩할 땐 오타를 잘 보아야 한다..(매우 중요)

     

    2022으로 다시 테스트해보니 정상적으로 작동한다 :)

    서버에 올려 실제 테스트를 해도 잘 작동했다.

    주나 월이 바뀌면 시간이 정상적으로 초기화되고 초기화된 날짜와 시간도 기록된다.

     

    현재 문제점은 아니지만 한 가지 의문점이라고 한다면 월 기록을 업데이트 한지 얼마 지나지 않아 또 업데이트를 하면 날짜는 정상기록되지만 시간과 분, 초는 업데이트하는 시간으로 기록되지 않는다는 것.

     

    코드는 바뀐게 없는데 30분 좀 더 지나고 나서 업데이트 했을 때는 정상적으로 시간, 분, 초까지 기록,

    2분 정도 지나고 나서 업데이트 했을 때는 연, 월, 일만 정상적으로 기록되었다.

     

    시간의 차이가 날만한 부분은 우선 시간을 한국 시간 기준으로 바꾸는 코드였다.

    // for local time
    
    // 1. 현재 PC 표준 시간
    const curr = new Date();
    
    // 2. UTC 시간 계산
    const utc = curr.getTime() + curr.getTimezoneOffset() * 60 * 1000;
    
    // 3. UTC to KST (UTC + 9시간)
    const KR_TIME_DIFF = 9 * 60 * 60 * 1000;
    const kr_curr = new Date(utc + KR_TIME_DIFF);

    여기에 쓰인 getTimezoneOffset()은 내 로컬 시간과 UTC 시간 간의 분의 차이를 나타내 준다.

    이 과정에서 초의 단위를 고려하지 않았지만 애초에 getTime()에 초의 단위가 들어가므로 문제가 없다.

    (애초에 국가간 시차는 1시간, 혹은 기껏해야 30분 단위이므로 문제가 없을 것이긴 하지만 말이다.)

     

    그렇다면 Mongo DB에서 날짜 데이터를 업데이트할 때 문제가 생기는 건가?

    깊이 있게 조사가 필요해보이니 우선은 프로젝트의 빠른 진행을 위해 넘기도록 하고 추후 여유가 될 때 찾아보도록 하자.

    현재로서는 이렇게 흘러가더라도 문제가 없고 해당 부분을 고친다고해도 무언가 더 나아지는 것은 없기 때문이다.

     

     

    이런 코드도 짰었고,, 꽤나 많은 노력을 한 끝에 지금의 코드를 완성하게 되었다.

    ////////////////// 시간 초기화가 마지막으로 이루어진 주차가 해당 연도에 몇 주차에 속해 있는지 구하기
              const lastUpdatedDate = await thatUser.lastUpdated;
              // 여기에 마지막 업데이트 된 날짜 넣어야함
    
              let oneJan = new Date(lastUpdatedDate.getFullYear(), 0, 1);
              let numberOfDays = Math.floor(
                (lastUpdatedDate - oneJan) / (24 * 60 * 60 * 1000)
              );
              let result = Math.ceil(
                (lastUpdatedDate.getDay() + 1 + numberOfDays) / 7
              );
              console.log(
                "Week Numbers of current date (" +
                  lastUpdatedDate +
                  ") is:" +
                  result
              );
    
              ////////////////방을 나가는 시점이 해당 연도 몇 주차에 속해 있는지 구하기
              const roomExitDate = new Date();
    
              let oneJan2 = new Date(roomExitDate.getFullYear(), 0, 1);
              let numberOfDays2 = Math.floor(
                (roomExitDate - oneJan2) / (24 * 60 * 60 * 1000)
              );
              let result2 = Math.ceil(
                (roomExitDate.getDay() + 1 + numberOfDays2) / 7
              );
              console.log(
                "Week Numbers of current date (" + roomExitDate + ") is:" + result2
              );
    
              // 각각의 날짜가 속한 주차가 같은지 혹은 같은 주차에 속해있지만 연도가 다른지
              if (
                result !== result2 ||
                lastUpdatedDate.getFullYear() !== roomExitDate.getFullYear()
              ) {
                const dateForLastUpdated = roomExitDate;
    
                await User.update({
                  where: {
                    id,
                  },
                  lastUpdated: dateForLastUpdated,
                });
    
                // 원하는 행을 찾아서 해당 행의 데이터 변경
                await WeekRecord.updateMany(
                  { userId: id },
                  {
                    $set: {
                      mon: 0,
                      tue: 0,
                      wed: 0,
                      thur: 0,
                      fri: 0,
                      sat: 0,
                      sun: 0,
                    },
                  }
                );
              }

     

    [vscode 파일명 옆 표시들]

     

    vs code를 다루다가 문득 A는 무엇인지 궁금해서 찾아보았다.

    다른 것들도 같이 있으니 간간히 참조하면 좋겠다.

    A - Added (This is a new file that has been added to the repository)

    M - Modified (An existing file has been changed)

    D - Deleted (a file has been deleted)

    U - Untracked (The file is new or has been changed but has not been added to the repository yet)

    C - Conflict (There is a conflict in the file)

    R - Renamed (The file has been renamed)

    S - Submodule (In repository exists another subrepository)

     

    [짰던 코드에 대한 팀원의 피드백]

     

    1. mysql에서 join 된 것 중 foreign key로 설정된 것들은 이미 그 테이블에 열로 추가되므로 모델에 별도로 해당 열을 지정해주어선 안된다. 해주면 열이 중복으로 발생하기 때문

     

    2. 자세히는 모르지만 함수와 메서드에는 차이가 있다.

    우리의 코드에서는 메서드를 가져오는 것이기에 괄호를 붙일 필요가 없다.

    예를 들면 아래와 같다.

     

    // 내가 쓴 코드
    const newBadge = await RoomController.delete.newBadge;
    
    //추천 코드
    const newBadge = await RoomController.delete.newBadge;

     

    3. 메서드는 비동기가 아니다. 따라서 비동기 처리를 해줄 필요는 없다.

    비동기 처리가 필요한 곳에만 async/await을 쓰는 게 좋다.

     

    const newBadge = await RoomController.delete.newBadge;
    
    // 이렇게 씀
    -> const newBadge = RoomController.delete.newBadge;

     

     

    ▶ 느낀 점

    멋진 팀원 분들을 만나 많은 것을 배우고 느끼고 있다.

    지금은 능숙하진 않지만 나도 머지않아 그런 멋진 사람이 될 수 있겠지.

    +

    여전히 알아야 할 것이 참으로 많다는 것을 또 느끼는 하루였다.

    기술이나 기능의 특성에 대해 제대로 알고 쓰는 것, 비슷한 다른 기술과 특징을 비교할 수 있는 것 등 IT 지식이 필요하다.

    그러기 위해서 열심히 찾아보아야겠다.

     

    물론 호기심이 있기에 지금 당장 찾아볼 수도 있겠지만 이미 많은 고민과 코드 작업 끝에 조금 피곤한 상태이다.

    모든 것은 아니더라도 하나씩 하나씩 찾아보고 공부해본다면 될 것이니 너무 스트레스 받지는 않기로 한다.

    누구나 처음은 쉽지 않은 법이니.

    화이팅팅 :)

     

    ▶ 공부 시 참고 링크들

     

    https://dev.to/dvddpl/how-to-kill-a-node-process-5d13

     

    How to kill a node process

    how to kill a running node process

    dev.to

     

     

     

    https://poiemaweb.com/js-scope

     

    Scope | PoiemaWeb

    스코프는 참조 대상 식별자(identifier, 변수, 함수의 이름과 같이 어떤 대상을 다른 대상과 식별할 수 있는 유일한 이름)를 찾아내기 위한 규칙으로 자바스크립트는 이 규칙대로 식별자를 찾는다.

    poiemaweb.com

     

    '항해 99' 카테고리의 다른 글

    항해 99 5기 TIL_80  (0) 2022.03.31
    항해 99 5기 TIL_79  (0) 2022.03.30
    항해 99 5기 TIL_73  (0) 2022.03.25
    항해 99 5기 TIL_72  (0) 2022.03.25
    항해 99 5기 TIL_71  (0) 2022.03.22
Designed by Tistory.