首页 > 解决方案 > 字符串星期日期到coldfusion日期

问题描述

我需要像这样格式化一个字符串日期:

2021-W46 

变成某种东西,我可以在冷融合parseDateTimedateFormat功能中使用。

W46在这种情况下是第 46 周。

我尝试的是直接将该字符串放入parseDateTimeand dateFormat,但两者都给了我一个错误,即我的输入不是正确的日期格式。

我怎样才能做到这一点?

编辑

我忘了提到我需要那周的第一天(在我的情况下是星期一)

标签: htmlcoldfusion

解决方案


使用 Wikipedia 中的算法从一周日期和您的输入格式计算序数或月份日期,此函数将从提供的 ISO 周编号格式返回星期一日期作为字符串传递给函数。

从星期日期计算序数或月份日期

算法:

  1. 将周数woy乘以 7。
  2. 然后加上工作日
  3. 从这个总和中减去当年的修正:
    • 获取 1 月 4 日的工作日。
    • 添加 3。
  4. 结果是序号日期,可以转换为日历日期。
    • 如果由此获得的序号日期为零或负数,则该日期属于上一个日历年;
    • 如果大于一年中的天数,则属于下一年。

可以在此处找到代码的工作要点。

<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>

推荐阅读