Jeremy Rajan
Jeremy Rajan

Reputation: 662

Format the following date into YYYY-mm-dd in JS

How would I go about converting following date:

Thu Feb 18 12:25:00 SGT 2016

into a format like '2016-02-18'?

I know,

  1. That, using a new Date(Date.parse('...')), with calls, will help me get it. But the problem being timezone part (SGT).
  2. I dont want to use any libraries out there.

What would be the effective way to go about this?

Any help is appreciated!

PS:

Ok, I have tried

new Date(Date.parse('Thu Feb 18 12:25:00 SGT 2016'))

but of-course, it is going to me 'invalid date' error.

Upvotes: 0

Views: 1076

Answers (4)

Buddhabhushan Kamble
Buddhabhushan Kamble

Reputation: 300

var date = "Thu Feb 18 12:25:00 SGT 2016";

date = date.replace("SGT","GMT+0800") // replaces SGT with GMT+0800 because 
singapore time is 8 hrs ahead than GMT timezone

var newdate = new Date(Date.parse(date))

var requiredDate = newdate.toLocaleDateString()

Upvotes: 0

MaDHaN MinHo
MaDHaN MinHo

Reputation: 529

var input="Thu Feb 18 12:25:00 SGT 2016";
  
var ar=input.split(" ");

  var months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"};

console.log(ar[ar.length-1]+"-"+months[ar[1]]+"-"+ar[2]);

  

Try this code no date parsing required. Please check on console for result.

Upvotes: 0

ElPedro
ElPedro

Reputation: 586

Why not just take the individual components of the date object and build a string from them?

full_date = new Date();
formatted_date_string = full_date.getFullYear() + "-" + (full_date.getMonth()+1) + "-" + full_date.getDate();

I'll leave it to you to sort out the leading 0s on the day and month.

Upvotes: 0

RobG
RobG

Reputation: 147523

I guess I should wait for you to post some code, but here's an example. It splits the string into parts, converts the month name to a number, then outputs the bits you want in the order you want. The slice on the month name is just in case you want to use the full month name, but maybe that's unnecessary:

function reformatDate(s){
  var b = s.split(/[\s:]/);
  var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
                jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
  return b[7] + '/' + months[b[1].toLowerCase().slice(0,3)] + '/' + ('0'+b[2]).slice(-2);
}

document.write(reformatDate('Thu Feb 18 12:25:00 SGT 2016'));

That format date string (y/m/d) isn't consistent with any standard that I know of and likely will not be parsed by most browsers.

Upvotes: 2

Related Questions