0

I have date in without "/" in text field and it is in mm/dd/yy format. We received input in this format 03292014. I want to get month,date and year from this number like 03/29/2014

var m = new Date(3292014*1000)

console.log(m.toGMTString())
2
  • 4
    There are so many answers about creating Date objects from strings and formatting a date string from a Javascript Date object here on SO. You should try to search a little harder, you can't miss them. Commented Mar 1, 2014 at 15:22
  • On way could be: use a regex to get the parts, build the date out of them. Commented Mar 1, 2014 at 15:24

2 Answers 2

4

You could do this :

var m = '03292014'.match(/(\d\d)(\d\d)(\d\d\d\d)/);
var d = new Date(m[3], m[1] - 1, m[2]);

Or convert the input into a standard "YYYY-MM-DD" format :

var d = new Date('03292014'.replace(
    /(\d\d)(\d\d)(\d\d\d\d)/, '$3-$1-$2'
));

Specs : http://es5.github.io/#x15.9.1.15.


According to Xotic750's comment, in case you just want to change the format :

var input = '03292014';
input = input.replace(
    /(\d\d)(\d\d)\d\d(\d\d)/, '$1/$2/$3'
);
input; // "03/29/14"
Sign up to request clarification or add additional context in comments.

Comments

1

Get the components from the input, then you can create a Date object from them. Example:

var input = '03292014';

var year = parseInt(input.substr(4), 10);
var day = parseInt(input.substr(2, 2), 10);
var month = parseInt(input.substr(0, 2), 10);

var date = new Date(year, month - 1, day);

6 Comments

Well, this is the simplest way to do this but considering that OP may get some other format in future, it is better to write a function that takes input as input string, input format and output format. Just a thought, usually that is my approach. Cheers!
If the OP is just looking to format 03292014 to 03/29/2014 then there isn't actually any need to use Date at all. A splice or slice only solution would be adequate. :)
@Xotic750: Yes, if that is what the OP wants to do. The code example in the question suggests that a Date object is the desired result.
I think you are just far too kind. ;)
@Xotic750 The title is very misleading here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.