'' This code is part of GrapeCity Documents for Word samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
Imports System.Drawing
Imports GrapeCity.Documents.Word

'' This sample shows how to add simple date and time fields to a Word document.
'' Note that GcWord does not yet support field calculation. But fields' values
'' calculated in code can be supplied for a field, as this sample demonstrates.
Public Class DateAndTime
    Function CreateDocx() As GcWordDocument
        Dim now = DateTime.Now

        Dim doc = New GcWordDocument()

        Dim p0 = doc.Body.Paragraphs.Add("DATE field with default formatting: ")
        Dim date0 = p0.GetRange().SimpleFields.Add("DATE", now.ToString("d"))
        p0.GetRange().Runs.Add(vbCrLf + "TIME field with default formatting: ")
        Dim time0 = p0.GetRange().SimpleFields.Add("TIME", now.ToString("t"))

        Dim p1 = doc.Body.Paragraphs.Add(
            "The following tables demonstrates some custom date/time formats. " +
            "The left column shows the field code, right column contains the actual field using that code.")

        '' Add and setup the table to contain the samples:
        Dim t = doc.Body.Tables.Add(0, 0)
        t.Style = doc.Styles.Add("Table style 1", StyleType.Table)
        For Each border In t.Style.Table.Borders
            border.LineStyle = LineStyle.Single
            border.LineWidth = 0.5F
            border.Color.RGB = Color.Black

        '' Sample DATE formats:
        Dim sampleDateFormats As String() =
                "DATE \@ ""M/d/yyyy""",
                "DATE \@ ""dddd, MMMM dd, yyyy""",
                "DATE \@ ""MMMM d, yyyy""",
                "DATE \@ ""M/d/yy""",
                "DATE \@ ""yyyy-MM-dd""",
                "DATE \@ ""d-MMM-yy""",
                "DATE \@ ""M.d.yyyy""",
                "DATE \@ ""MMM. d, yy""",
                "DATE \@ ""d MMMM yyyy""",
                "DATE \@ ""MMMM yy""",
                "DATE \@ ""MMM-yy""",
                "DATE \@ ""M/d/yyyy h:mm am/pm""",
                "DATE \@ ""M/d/yyyy h:mm:ss am/pm""",
                "DATE \@ ""h:mm am/pm""",
                "DATE \@ ""h:mm:ss am/pm""",
                "DATE \@ ""HH:mm""",
                "DATE \@ ""'Today is 'MMMM d, yyyy"""

        '' Add sample format strings and corresponding fields:
        For Each fmt In sampleDateFormats
            Dim r = t.Rows.Add(New String() {fmt})

            '' GcWord does Not yet support field calculation, but it does allow
            '' to provide values calculated in code, so that's what we do here.
            '' We use the fact that most date/time format strings are the same
            '' in Word And .NET, but do replace Word's 'am/pm' with .NET 'tt':
            Dim f = fmt.Substring("DATE \@ ".Length).Trim("""").Replace("am/pm", "tt")
            r.Cells.Add().GetRange().Paragraphs.First.GetRange().SimpleFields.Add(fmt, now.ToString(f))

        '' Done:
        Return doc
    End Function
End Class