Home > Software design >  Cannot implicitly convert type 'string' to 'System.DateTime' in C#
Cannot implicitly convert type 'string' to 'System.DateTime' in C#

Time:07-28

I am working on an XSLT that uses a C# script.

I have a function DateParse that is supposed to take a string which is a date stored as "yyyy-MM-dd". I want it to return the string as a date stored as "yyyyMMdd"

I tried the following (among other things):

public DateTime DateParse(string dateString)
{
     string result = DateTime.ParseExact(dateString, "yyyyMMdd",
                     System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
     return result;
     }

However, I am getting the following error:

Cannot implicitly convert type 'string' to 'System.DateTime'

Anyone have any ideas? I am lost and have tried so much.

Kind regards

Edit:

As requested, I am sharing the xslt code that executes the C# function here.

<xsl:variable name="ExtractDate" select="ms:DateParse(/Extraction/Row[1]/AsOfDate)" />

AsOfDate is a column in a xlsx file that contains values 2021-09-10, or any date in the format yyyy-MM-dd

CodePudding user response:

I don't see how 2021-09-10 would parse with DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).

I guess you want e.g. DateTime.ParseExact(dateString, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture).

CodePudding user response:

You just want to remove the - characters from the date string?

That's simple to do in pure XSLT using the XPath translate function to convert the - characters to a zero-length string.

Sample input:

<Extraction>
  <Row>
    <AsOfDate>2021-09-10</AsOfDate>
  </Row>
</Extraction>

XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
      <xsl:variable name="ExtractDate" select="
        translate(
          /Extraction/Row[1]/AsOfDate[1], 
          '-', 
          ''
        )
      "/>
      <result><xsl:value-of select="$ExtractDate"/></result>
    </xsl:template>
</xsl:stylesheet>

Result:

<result>20210910</result>
  • Related