Parse a String to a Date Object

The following sample parses a string (formatted according to the user’s preferences) to a raw Date object, and then parses it back to the formatted string. This sample uses format.parse(options) and format.format(options).

This sample assumes the Date Format set in the preferences is MM/DD/YYYY. You may need to change the value for the date used in this script to match the preferences set in your account.

Note:

This sample script uses the require function so that you can copy it into the SuiteScript Debugger and test it. You must use the define function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.

          /**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */
define(['N/ui/serverWidget', 'N/format'], function(serverWidget, format) {
    function parseAndFormatDateString() {
        // Assuming Date format is MM/DD/YYYY
        var initialFormattedDateString = "07/28/2015";
        var parsedDateStringAsRawDateObject = format.parse({
            value: initialFormattedDateString,
            type: format.Type.DATE
        });
        var formattedDateString = format.format({
            value: parsedDateStringAsRawDateObject,
            type: format.Type.DATE
        });
        return [parsedDateStringAsRawDateObject, formattedDateString];
    }
    function onRequest(context) {
        var data = parseAndFormatDateString();

        var form = serverWidget.createForm({
            title: "Date"
        });

        var fldDate = form.addField({
            type: serverWidget.FieldType.DATE,
            id: "date",
            label: "Date"
        });
        fldDate.defaultValue = data[0];

        var fldString = form.addField({
            type: serverWidget.FieldType.TEXT,
            id: "dateastext",
            label: "Date as text"
        });
        fldString.defaultValue = data[1];

        context.response.writePage(form);
    }
    return {
        onRequest: onRequest
    };
}); 

        

General Notices