我需要格式化一个字符串日期,如下所示:
2021-W46
变成我可以在冷融合中使用的东西parseDateTime
or dateFormat
功能。
W46
在本例中是第 46 周。
我尝试的是直接将该字符串放入parseDateTime
and dateFormat
,但两者都给了我一个错误,即我的输入不是正确的日期格式。
我怎样才能做到这一点?
Edit:
我忘了提到我需要那周的第一天(在我的例子中是星期一)
使用维基百科的算法从一周日期计算序数日期或月份日期和您的输入格式,此函数将从以字符串形式传递给函数的提供的 ISO 周编号格式返回星期一日期。
从周日期计算序数日期或月份日期
算法:
- 乘以周数woy by 7.
- 然后添加工作日编号dow.
- From this sum subtract the correction for the year:
- The result is the ordinal date, which can be converted into a calendar date.
- 如果由此获得的序数日期为零或负数,则该日期属于上一个日历年;
- 如果大于该年的天数,则属于下一年。
![](https://wikimedia.org/api/rest_v1/media/math/render/svg/1ceefb06904e8bd12867e276d7ba330d2d0a4976)
可以找到代码的工作要点here.
<cffunction name="weekOfYear" returnType="date">
<cfargument name="yearWeek" type="string">
<!--- Parse out the year, the week of the year from arguments.yearWeek and default the day of week to Monday --->
<cfset year = listGetAt(arguments.yearWeek, 1, "-W")>
<cfset woy = listGetAt(arguments.yearWeek, 2, "-W")>
<cfset dow = 2>
<!--- Calculate the number of days this year and last year for later use. --->
<cfset DaysThisYear = daysInYear(CreateDate(year, 1, 1))>
<cfset DaysLastYear = daysInYear(CreateDate(year-1, 1, 1))>
<!--- Multiply week number "woy" by 7, then add the weekday number "dow" --->
<cfset ordinalDate = woy*7 + dow>
<!--- From this sum, subtract the correction for the year: Get the weekday of 4 January and add 3 --->
<cfset ordinalDate = ordinalDate - (dayOfWeek(parseDateTime("#year#-01-04", "y-M-d")) + 3)>
<!--- The result is the ordinal date, which can be converted into a calendar date. --->
<cfif ordinalDate LT 1>
<!--- If the ordinal date thus obtained is zero or negative, the date belongs to the previous calendar year. --->
<cfset ordinalDate = ordinalDate + daysLastYear>
<cfset year = year-1>
<cfelseif ordinalDate GT daysThisYear>
<!--- If it is greater than the number of days in the year, it belongs to the following year. --->
<cfset ordinalDate = ordinalDate - daysThisYear>
<cfset year = year+1>
</cfif>
<cfreturn parseDateTime("#year#-#ordinalDate#", "y-D")>
</cffunction>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)