XSLT 3.0日期格式转换求助:指定格式转yyyy-mm-dd带AM/PM时间
Solution for Converting Date Format in XSLT 3.0
Since you're working with XSLT 3.0, we can leverage built-in XPath 3.0 date/time parsing and formatting functions to handle this conversion without any extension scripts like <msxsl:script>. Here's a step-by-step solution:
Approach
- Parse the Input String: Convert the human-readable date string to an
xs:dateTimevalue usingparse-dateTime(), specifying the exact format of your input and using the English locale to recognize month/weekday names. - Format the Date-Time: Convert the parsed
xs:dateTimeback to a string in your desired format usingformat-dateTime().
Complete XSLT Example
This example assumes your date string is in a <pubDate> element (adjust the match pattern if your date is in a different element like dc:date):
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <!-- Identity template: copy all nodes except those we explicitly transform --> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <!-- Transform the date string to the desired format --> <xsl:template match="pubDate"> <xsl:copy> <!-- Clean up any extra whitespace in the input --> <xsl:variable name="clean-date" select="normalize-space(.)"/> <!-- Parse the date string into an xs:dateTime value --> <xsl:variable name="parsed-datetime" select="parse-dateTime( $clean-date, 'EEEE, MMMM d, yyyy - HH:mm', 'en' )"/> <!-- Format to yyyy-mm-dd hh:mm AM/PM --> <xsl:value-of select="format-dateTime( $parsed-datetime, '[Y0001]-[M01]-[D01] [h01]:[m01] [Pn,*]', 'en' )"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
Key Details
- Parsing Format:
'EEEE, MMMM d, yyyy - HH:mm'matches your input pattern:EEEE: Full weekday name (e.g., "Tuesday")MMMM: Full month name (e.g., "January")d: Day of the month (1-31, with or without leading zero)yyyy: 4-digit yearHH:mm: 24-hour time format
- Formatting Pattern:
'[Y0001]-[M01]-[D01] [h01]:[m01] [Pn,*]'creates your desired output:[Y0001]: 4-digit year (e.g., "2018")[M01]: 2-digit month (e.g., "01")[D01]: 2-digit day (e.g., "29")[h01]: 12-hour time (e.g., "10")[m01]: 2-digit minutes (e.g., "10")[Pn,*]: Uppercase AM/PM indicator (e.g., "AM")
- Locale: The
'en'locale ensures English month/weekday names are parsed correctly, and AM/PM is formatted as expected.
Notes
- This requires an XSLT 3.0-compliant processor (like Saxon, Altova XMLSpy, or Oxygen XML Editor).
- Ensure your input date string strictly follows the pattern
星期几,月份 日,年份 - 时间; variations (e.g., missing commas, extra characters) will cause parsing errors. normalize-space()handles any leading/trailing whitespace or extra spaces in the input string to avoid parsing issues.
内容的提问来源于stack exchange,提问作者Rohit Gupta
相关产品推荐
相关产品推荐

