0

I want to display today's date along with a string. Eg., I want to display R_20160310 in a field. I used the following code, I'm not able to get the date format in YYYYMMDD when I store a string value in scope. Below are the codes in my html and controller.

html:

<tr>
              <th><label>Review Title/Purpose*</label></th>
              <td><input type="text" class="col-md-10" ng-model="today"></td>
          </tr>

Controller:

$scope.today= 'Review__' + new Date();

Right now I'm getting as, "Review__Mon Oct 03 2016 10:47:47 GMT+0800 (Malay Peninsula Standard Time)" but I need to display "Review_20160310". Any suggestions?

SURYA VISWANATHAN
  • 187
  • 1
  • 3
  • 12
  • where did you *try* to change the date format? It looks like you just output `Date()` in it's default format. – Claies Oct 03 '16 at 02:50
  • 1
    Possible duplicate of [How to format a JavaScript date](http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Cine Oct 03 '16 at 02:53
  • @Claies Where should I include the format? I know it's taking default format. But I'm unaware where to include the format. – SURYA VISWANATHAN Oct 03 '16 at 03:16

3 Answers3

3

Take advantage of angular's built in date filter

 $scope.today= 'Review__' +  $filter('date')(new Date(), 'yyyyMMdd'[,timezone])
charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

Try this.

function x() {
  var y = new Date();
  return 'Review_' + ((y.getFullYear() + ' ' + (y.getMonth() + 1) + ' ' + y.getDate()).replace(/ /g, ''));
}

console.log(x());
kind user
  • 40,029
  • 7
  • 67
  • 77
0

Run the date through a helper function to parse it:

UPDATE CALL:

$scope.today= 'Review__' + dateConvert(new Date());

HELPER FUNCTION:

function dateConvert(dateobj){
  var year = dateobj.getFullYear();
  var month= ("0" + (dateobj.getMonth()+1)).slice(-2);
  var date = ("0" + dateobj.getDate()).slice(-2);
  var hours = ("0" + dateobj.getHours()).slice(-2);
  var minutes = ("0" + dateobj.getMinutes()).slice(-2);
  var seconds = ("0" + dateobj.getSeconds()).slice(-2);
  var day = dateobj.getDay();
  var months = ["01","02","03","04","05","06","07","08","09","10","11","12"];
  var converted_date = "";

  converted_date = year + month + date;

  return converted_date;

}

https://jsfiddle.net/93ds6md0/

jeremykenedy
  • 4,150
  • 1
  • 17
  • 25