fedect1 / graduation-project-fedect1

graduation-project-fedect1 created by GitHub Classroom
MIT License
1 stars 0 forks source link

Is this your own NPM library? #21

Open Dr4gon opened 1 year ago

Dr4gon commented 1 year ago

@fedect1 How would u feel about cleaning this up, adding tests, and publishing it as a cool declarative DayFormat lib?

formatDay.js

import { defineStore } from 'pinia'
import axios from 'axios'

axios.defaults.withCredentials = true
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL

export const useFormatDay = defineStore('formatDay', {
  actions: {
    async formatDay(dateStr) {
      const date = new Date(dateStr)
      if (isNaN(date.getTime())) {
        return 'Invalid Date'
      }
      const dayPassed = Math.floor((Date.now() - date.getTime()) / (1000 * 60 * 60 * 24))
      if (dayPassed === 0) {
        return 'Today'
      } else if (dayPassed === 1) {
        return 'Yesterday'
      } else if (dayPassed < 7) {
        return `${dayPassed} days ago`
      } else if (dayPassed < 30) {
        return `${Math.floor(dayPassed / 7)} weeks ago`
      } else if (dayPassed < 365) {
        return `${Math.floor(dayPassed / 30)} months ago`
      } else {
        return `${Math.floor(dayPassed / 365)} years ago`
      }
    }
  }
})