How to make date.toString keeping local date?

I used this code to serialize a date js object for a string,

but for the April 12thdate translates to April 11t.

self.dateToString = function (date) {
                    return (date === null || !(date instanceof Date)) ? null : date.toISOString().slice(0, 10);
                    //return (date === null || !(date instanceof Date)) ? null : dateFormat(date, "dd mmmm yyyy");
                }

how can i fix this?

enter image description here

+4
source share
2 answers

time zone = UTC is set, and then just add the function to the controller by passing the date -

function dateToString (date){
     var d = new Date(date),
     month = '' + (d.getMonth() + 1),
     day = '' + d.getDate(),
     year = d.getFullYear();

 if (month.length < 2) month = '0' + month;
 if (day.length < 2) day = '0' + day;

 return [year, month, day].join('-');

}

he will return the date.

it worked for me :)

0
source

You are using Angular, and Angular has a nice little filter that perfectly parses JavaScript dates.

(function() {
	'use strict';
  
  angular.module('myApp', []);
  
  angular.module('myApp').controller('MyController', MyController);
  
  MyController.$inject = ['$filter'];
  function MyController($filter) {
  	var vm = this;
    vm.doMagic = function() {
    	return vm.dateToString(new Date("04/12/2017"));
    }
    vm.dateToString = function (date) {
      return (date === null || !(date instanceof Date)) ? null : $filter("date")(date, "dd MMMM yyyy");
    }
  }
  
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<html>
<body ng-app="myApp">
  <div ng-controller="MyController as main">
    {{main.doMagic()}}
  </div>
</body>
</html>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1674092/


All Articles