Search code examples
javascriptdatedojodate-format

Formatting ddmmyy in DOJO


I have a JSON file which has the following key value pair.

"emvtag1"="currentdate"
"emvtag2"="currenttime"

I need to use DOJO to replace the currentdate and currenttime.

This is my code:

formatDate: function(d) {
  //get the month
  var month = d.getMonth();
  //get the day
  //convert day to string
  var day = d.getDate().toString();
  //get the year
  var year = d.getFullYear();

  //pull the last two digits of the year
  year = year.toString().substr(-2);

  //increment month by 1 since it is 0 indexed
  //converts month to a string
  month = (month + 1).toString();

  //if month is 1-9 pad right with a 0 for two digits
  if (month.length === 1) {
    month = "0" + month;
  }

  //if day is between 1-9 pad right with a 0 for two digits
  if (day.length === 1) {
    day = "0" + day;
  }

  //return the string "MMddyy"
  return month + day + year;
}

SResp: function(act) {
  var event = JSON.parse(data);
  if (action === "okEMVHost") {
    var d = new Date();
    emvtag1 = this.formatDate(d);
    emvtag2 = this.formatDate(d);

  }
}

I know thats how it will work in JAvascript, the formatteddate(d) function, not sure if it will be like this in DOJO.


Solution

  • In the Dojo , in order to format date , use the dojo/date/locale ::format() function as below ,

    locale.format( date, {selector:"date", datePattern:"ddMMyy" } );
    

    You can see the above snippet with working different format

    require(["dojo/date/locale"
    ], function(locale) {
      var date = new Date();
      
      var format1 = locale.format( date, {selector:"date", datePattern:"ddMMyy" } );
      
      var format2 = locale.format( date, {selector:"date", datePattern:"MM-dd-yyyy" } );
      
        var format3 = locale.format( date, {selector:"date", datePattern:"MM / dd / yyyy ss:mm:SSS" } );
        
        
      console.log("ddMMyy -----> ", format1);
      console.log("MM-dd-yyyy -> ",format2);
      console.log("MM /dd/yyyy ss:mm:SSS -> ",format3);
      
    });
    <link href="//ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css" rel="stylesheet" />
    <script>
      dojoConfig = {
        parseOnLoad: true,
        async: true
      };
    </script>
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"></script>