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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Gertone (Geert Bormans)Information 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Gertone (Geert Bormans)Information 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
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

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


Cd&
0
Gertone (Geert Bormans)Information 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
Gertone (Geert Bormans)Information 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
Gertone (Geert Bormans)Information 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
Gertone (Geert Bormans)Information 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
Gertone (Geert Bormans)Information 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
Gertone (Geert Bormans)Information ArchitectCommented:
welcome
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.