-4

I need to format my date like this "2016-04-19T03:35:17.02". How can i format date format like using javascript or jQuery.

Please help me any one this.

bagya
  • 325
  • 1
  • 7
  • 32

2 Answers2

-1

In javascript you have a Date object. First you must create the object:

var d = new Date();

Then you can make a variable for each of the pieces you want:

// Get the year
var year = d.getFullYear();

// Get the month +1 because normally returns 0-11
var month = d.getMonth()+1;

// Format month to add a 0 if 1-9
var fMonth = month < 9 ? '0' + month : month;

// Get day and format it to add a 0 if 1-9
var fDay =  d.getDate() < 9 ? '0' + d.getDate() : d.getDate();

// Combine it into a single string
var dateStr = year +'-'+ fMonth +'-'+ fDay +'T';

That should get you "2016-05-22T". The rest you can complete on your own. You can use w3schools list of available Date methods: http://www.w3schools.com/jsref/jsref_obj_date.asp

Tyler
  • 3,519
  • 5
  • 32
  • 54
  • There's a single method that'd do this for the asker, but evidently they did not research their issue before coming here for help. Assisting them anyway just proves them that their question was welcome while in fact it was not. – SeinopSys May 21 '16 at 17:04
  • Yeah, it's fine though, I had the time and wanted to take the opportunity to share with him some Javascript knowledge – Tyler May 21 '16 at 17:07
-2

You can use these methods getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), getMilliseconds() or just some library like Moment.js, where you can just use method .format() and it's parameters.

flppv
  • 3,061
  • 3
  • 23
  • 41