【问题标题】:How to get start and end timestamps of every month in selected year如何获取选定年份中每个月的开始和结束时间戳
【发布时间】:2021-11-16 00:59:55
【问题描述】:
所以我有年初(2021 年 1 月 1 日星期五 00:00:00)和年末(2021 年 12 月 31 日星期五 23:59:59)的时间戳
{ yearStart: 1609455600000, yearEnd: 1640991599000 }
因为我需要获取今年每个月的数据,所以我需要一个月的开始和结束时间戳。
有什么方法吗?提前联系
【问题讨论】:
标签:
javascript
sql
node.js
reactjs
unix-timestamp
【解决方案1】:
我建议使用日期和时间模块。例如dayjs
有像 startOf('month') 或 add() 这样的助手。
这是关于您的问题的模块的一些伪代码。我建议你学习它,因为日期和时间现在在很多项目中都很方便。
const dayjs = require('dayjs')
// Initialise dayjs object with your provided start of year timestamp.
const startOfYear = dayjs(1609455600000)
// set to start end endof month
const january_start = startOfYear.startOf('month')
const january_end = startOfYear.endOf('month')
// add one month and set to start resp. end of
const february_start = startOfYear.add(1, 'month').startOf('month')
const february_end = startOfYear.add(1, 'month').endOf('month')
// ... loop and go further..
// Helper function for getting back javascript dates.
const numeric_date = startOfYear.toDate().getTime()
// there is also a format() function which allows printing
// nice looking dates.
startOfYear.format('MMM DD YYYY') // => prints 01 Jan 2021
更多信息请阅读docs
【解决方案2】:
使用以下代码创建存储过程或表值函数。根据需要格式化输出。
declare @year varchar(4)
set @year = '2022'
; with cte as
(select 0 'n' union select 1 union select 2 union select 3 union select 4 union select 5 union select 6
union select 7 union select 8 union select 9 union select 10 union select 11)
select dateadd(month, n, '1/1/'+@Year) 'yearStart'
, dateadd(second, -1, dateadd(month, n +1, '1/1/'+@Year)) 'yearEnd'
from cte