How to get today's date in XSL?

Hi,
I need to generate today's date using XSL function in the format MM/dd/yyyy? Is there a function in XSL? Thanks for any help.
ipjyoAsked:
Who is Participating?
 
Geert BormansInformation ArchitectCommented:
If you are using XSLT2, there is a function current-date()
and you can use format-date() to get the format you want

In XSLT1 there is no such function

There are some options
- pass the date in as a parameter from an external process. eg. if you start the XSLT from  ASP or java, get the current date in the C# or java and pass it to the XSLT as a parameter
- use an extension function to get the current date, that could be java or javascript or... this makes your code processor dependent. For that I need to know which processor you are using. I prefer the first option
- a variant of that is the exslt date() function, supported by the processors listed on this page http://exslt.org/date/functions/date/index.html

I would like some extra information
- how do you call the XSLT
- which processor are you using
0
 
COBOLdinosaurCommented:
<xsl:stylesheet 
    xmlns:ex="http://exslt.org/dates-and-times" 
    extension-element-prefixes="ex">

       <xsl:value-of select="ex:date-time()"/>
</xsl:stylesheet>

Open in new window



Cd&
0
 
Geert BormansInformation ArchitectCommented:
It is worthwhile noting that Cd&s solution only works with
Saxon 6.5, Xalan-J (which is the standard in java) , 4XSLT or libxslt (which also is the basis for the python and ruby XSLT processor)
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
COBOLdinosaurCommented:
I'm glad I posted. Now I get to expand my knowledge in a topic I am a little thin on.  :^)


Cd&
0
 
Geert BormansInformation ArchitectCommented:
One important processor missing from the equation is the microsoft one.
I have a stylesheet below that gets the date through the javascript scripting engine (as an extension function)
but note that this only works with the microsoft processors
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:date="http://yourdomain.org/dates-and-times"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                extension-element-prefixes="date msxsl">
<!-- you need to invent a namespace for your extension function, 
(the one prefixed by date: in this example),
because extension functions require their own namespace
you also need to declare the msxsl namespace,
prefixed by msxsl: here, to make the xsl processor aware you are dealing with a special script block
then you need to set both namespaces (by theiur prefix) as extension element prefixes -->

<!-- in an msxsl:script block you define the function,
you need to express the language (C# or VBS work as well)
and indicate which namespace the functions belongs to in the "implements-prefix" attribute
-->
<msxsl:script language="JScript" implements-prefix="date">
	<![CDATA[
		function  currentDate(){
    	var d = new Date();
		return d.getYear() + "-" + d.getMonth() + "-" + d.getDay();
		};
	]]>
</msxsl:script>
<!-- and just call the function -->
<xsl:template match="/">
	<xsl:value-of select="date:currentDate()"/>
</xsl:template>
<!-- NOTE: this technique binds your XSLT to MS XSLT processors only
That is why I prefer passing in a parameter -->

</xsl:stylesheet>

Open in new window

0
 
Geert BormansInformation ArchitectCommented:
@Cd&
glad to see you're back. did not realise you were visiting EE again.
must have been years since I last came accross one of your (always excellent) posts
0
 
COBOLdinosaurCommented:
Was gone 6 years, but I came back in the middle of Oct.  


Cd&
0
 
ipjyoAuthor Commented:
Thank you both for your input. I am using XSLT processor 1.0.
Please find the code attached. It has a function Transform_XPath_Expression() which takes xml and xsl and return the value.

Thank you.
Private Function LoadEmptyXsl() As String
        Dim xslData As String = _
            "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" & Environment.NewLine _
          & "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:date=""http://exslt.org/dates-and-times"" extension-element-prefixes=""date""> " & Environment.NewLine _
          & "<xsl:template match=""/"" > " & Environment.NewLine _
          & "{0}" & Environment.NewLine _
          & "</xsl:template>" & Environment.NewLine _
          & "</xsl:stylesheet>"
        Return xslData
    End Function


Dim supplementalSegment As New Xml.XmlDocument
supplementalSegment.Load(inXMLFile)

Dim strXslEmpty As String = LoadEmptyXsl()
Dim strXPath As String

strXPath = "<xsl:variable name="date" select="current-date()" />
<xsl:value-of select="substring($date, 6, 2)" />
<xsl:text>/</xsl:text>
<xsl:value-of select="substring($date, 9, 2)" />
<xsl:text>/</xsl:text>
<xsl:value-of select="substring($date, 1, 4)" />"

Dim strFieldValue As String = Transform_XPath_Expression(strXslEmpty, supplementalSegment, strXPath)

Public Function Transform_XPath_Expression(ByVal transformFormatString As String, ByVal supplementalSegment As XmlNode, ByVal xpath As String) As String

        
        Dim transform As New Xsl.XslCompiledTransform
        Dim stream As System.IO.MemoryStream
        Dim reader As XmlReader
        Dim writer As New System.IO.StringWriter
        Dim strXsl As String

        Try
            strXsl = String.Format(transformFormatString, xpath)
            'stream = StringToStream(strXsl)
            stream = New MemoryStream(System.Text.Encoding.ASCII.GetBytes(strXsl))
            reader = XmlReader.Create(stream)

            Try
                transform.Load(reader)
            Catch ex As XsltException
                WriteLog("Transform_XPath_Expression", "Invalid Import Field ""#" & xpath & """. " & ex.GetBaseException.ToString() & " Continuing program execution.", EventLogEntryType.Error)
                Return ""
            End Try

            transform.Transform(supplementalSegment, Nothing, writer)
            ' Output_iosw contains "<?xml version="1.0" encoding="utf-16"?>value_that_I_want"
            Dim writeroutput As String = writer.ToString()
            Dim gtPos As Integer = writeroutput.IndexOf(">")

            Return writeroutput.Substring(gtPos + 1, writeroutput.Length - (gtPos + 1))
        Catch e As Exception
            WriteLog("Transform_XPath_Expression", e.GetBaseException().ToString, EventLogEntryType.Error)
            Return ""
        End Try
    End Function

Open in new window

0
 
Geert BormansInformation ArchitectCommented:
This seems vb.net, so microsoft indeed
you will need the microsoft XSLT I posted last

Why do you type the XSLT out as a string,
you could load it from a file, that is a lot more robust
0
 
ipjyoAuthor Commented:
Actually that xslt string gets loaded from database at runtime and for some reasons it was implemented this way by another developer. I copied that xslt string into the code snippet just to show you. Thanks for your help. I will try the code in your  previous post and let you know.
0
 
ipjyoAuthor Commented:
For some reason, I have changed it to use xslt 2.0 and tried current-date() function but it is saying the below error. Any ideas please?

current-date() is an unknown XSLT function.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Dim fieldValue As String
        Dim oExtraData As New XmlDocument
        Dim strXslEmpty As String = LoadNewEmptyXsl()
        Dim fieldName As String = "<xsl:value-of select=""fn:current-date()""/>"

        Dim inXMLFile As String = "C:\temp\505131.xml"
        oExtraData.Load(inXMLFile)
        fieldValue = Transform_XPath_Expression(strXslEmpty, oExtraData, fieldName)

        MessageBox.Show("fieldvalue: " + fieldValue)

    End Sub

    Private Function LoadNewEmptyXsl() As String
        Dim xslData As String = _
            "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" & Environment.NewLine _
          & "<xsl:stylesheet version=""2.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">" & Environment.NewLine _
          & "<xsl:template match=""/"" > " & Environment.NewLine _
          & "{0}" & Environment.NewLine _
          & "</xsl:template>" & Environment.NewLine _
          & "</xsl:stylesheet>"
        Return xslData
    End Function

    Public Function Transform_XPath_Expression(ByVal transformFormatString As String, ByVal supplementalSegment As XmlNode, ByVal xpath As String) As String

        ' XPath Expression is a string, XMLFile is a URI string - Output of the Transform is a single parsed value that is 
        ' returned as a string

        ' BXG 4/30/09 - Perform a Transform on an XML File, using an XSL Style Sheet (memory variable), to produce 
        ' a string output. Current code handled WebBridge Admin expressions that start with // and that had attributes '~'.  
        ' The Transform allows the use of single XPath Expressions/Functions that do not begin with //.
        Dim transform As New Xsl.XslCompiledTransform
        Dim stream As System.IO.MemoryStream
        Dim reader As XmlReader
        Dim writer As New System.IO.StringWriter
        Dim strXsl As String

        Try
            strXsl = String.Format(transformFormatString, xpath)
            'stream = StringToStream(strXsl)
            stream = New MemoryStream(System.Text.Encoding.ASCII.GetBytes(strXsl))
            reader = XmlReader.Create(stream)

            Try
                transform.Load(reader)
            Catch ex As XsltException
                Return ""
            End Try

            transform.Transform(supplementalSegment, Nothing, writer)
            ' Output_iosw contains "<?xml version="1.0" encoding="utf-16"?>value_that_I_want"
            Dim writeroutput As String = writer.ToString()
            Dim gtPos As Integer = writeroutput.IndexOf(">")

            Return writeroutput.Substring(gtPos + 1, writeroutput.Length - (gtPos + 1))
        Catch e As Exception
            MessageBox.Show(e.Message)
            Return ""
        End Try
    End Function

Open in new window

0
 
ipjyoAuthor Commented:
I have also tried the attached code with xslt 2.0 but it was saying

Conversion from string "<msxsl:script language="JScript"" to type 'Double' is not valid.
Private Function LoadNewEmptyXsl() As String
        Dim xslData As String = _
            "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" & Environment.NewLine _
          & "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:date=""http://yourdomain.org/dates-and-times"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" extension-element-prefixes=""date msxsl""> " & Environment.NewLine _
          & "<msxsl:script language=""JScript"" implements-prefix=""date""> <![CDATA[ function  currentDate(){var d = new Date(); return d.getMonth() + " / " + d.getDay() + " / " + d.getYear();};]]> </msxsl:script>" & Environment.NewLine _
          & "<xsl:template match=""/"" > " & Environment.NewLine _
          & "{0}" & Environment.NewLine _
          & "</xsl:template>" & Environment.NewLine _
          & "</xsl:stylesheet>"
        Return xslData
    End Function

Open in new window

0
 
Geert BormansInformation ArchitectCommented:
I might not have been explicit about this.
For XSLT2 you need an XSLT2 processor
Microsoft has no XSLT2 processor,
so unless you do the effort of integrating saxon .net (www.saxonica.com)
you will have to live with XSLT1 functionality
0
 
ipjyoAuthor Commented:
I am sorry. I meant to say that I tried the javascript function with xslt 1.0 as you suggested earlier. I was receiving the below error. It looks like there is some string formatting error in my code (attached) but have not been able to figure out.

Conversion from string "<msxsl:script language="JScript"" to type 'Double' is not valid.

Thank you!
Private Function LoadNewEmptyXsl() As String
        Dim xslData As String = _
            "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" & Environment.NewLine _
          & "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:date=""http://yourdomain.org/dates-and-times"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" extension-element-prefixes=""date msxsl""> " & Environment.NewLine _
          & "<msxsl:script language=""JScript"" implements-prefix=""date""> <![CDATA[ function  currentDate(){var d = new Date(); return d.getMonth() + " / " + d.getDay() + " / " + d.getYear();};]]> </msxsl:script>" & Environment.NewLine _
          & "<xsl:template match=""/"" > " & Environment.NewLine _
          & "{0}" & Environment.NewLine _
          & "</xsl:template>" & Environment.NewLine _
          & "</xsl:stylesheet>"
        Return xslData
    End Function

Open in new window

0
 
Geert BormansInformation ArchitectCommented:
Honestly I have no clue,
teh VB seems to think this is a double instead of a string,
I have no clue why this happens, but it is VB thing, not an XSLT issue

on that line five, you are escaping a javascript in a XML CDATA which in turn you are escaping inside a VB string.
At some point you just have too much indirections.
I strongly recommend that you put the XSLT somewhere outside a bunch of VB string concats, it will be a hell more robust
0
 
ipjyoAuthor Commented:
Thank you very much for your help on this.
I agree and definitely put that code outside the vb code and try this again.
0
 
Geert BormansInformation ArchitectCommented:
welcome
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.