angularui bootstrap datepicker one day off

The angularUI’s datePicker widget returns back a js Date object with Eastern Time Zone. If I pass it back directly to the server, the Spring GsonHttpMessageConverter will try to convert it back to the UTC which is 5 hours earlier. This might cause one day off if the request is made after 7PM.

So I have to pass the String Date to the server. Several ways to convert it:

  1. Using Date.js:http://www.datejs.com/
    1. var date = Date.parse('2010-08-10');
      console.log(date.toString('dd-MMM-yyyy'));
  2. Using the newer moment.js which is widely used in Nodejs: http://momentjs.com/docs/#/displaying/
  3. using angular’s internal filter to format: https://docs.angularjs.org/api/ng/filter/date
    $filter('date')(date, format, timezone)
  4. use native javascript
    var date = new Date();
    
    function toLocal (date) {
    	var local = new Date(date);
    	local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    	return local.toJSON();
    }
    
    function toJSONLocal (date) {
    	var local = new Date(date);
    	local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    	return local.toJSON().slice(0, 10);
    }
    
    
    // check out your devtools console
    console.log(date.toJSON());
    console.log(date.toISOString());
    console.log(toLocal(date));
    
    console.log(toJSONLocal(date));
    

More

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s