Javascript to get date & time without chars and spaces

tmajor99
tmajor99 used Ask the Experts™
on
I need a javascript that will get the current date time and then strip off all spaces and chars.  

For example;

Fri 01 22 2016 20:09:23 GMT-0500 (Eastern Standard Time)

Remove all spaces and chars:  01222016200923
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Hi,
I recommend using the moment.js Javascript project. It makes working with dates very easy. See this plunker for an example.

There are two steps to using:
1: Include the project dependency.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>

Open in new window

 
2: Convert your date.
    <script>
      var formatDate= 'Fri 01 22 2016 20:09:23 GMT-0500 (Eastern Standard Time)';
      var responseDate = moment(formatDate).format('MMDDYYYYHHmmss');
      
      console.log(responseDate);
    </script>

Open in new window

Expert of the Year 2008
Top Expert 2008
Commented:
try:
function cleanDate(str){
return str.replace(/ GMT.+$/g,'').replace(/\D/g,'');
}

var str='Fri 01 22 2016 20:09:23 GMT-0500 (Eastern Standard Time)';

var result = cleanDate(str);
alert( result );

Open in new window

Bill PrewIT / Software Engineering Consultant
Top Expert 2016

Commented:
If you do want to do it in just native JavaScript, then here is a straight forward (not overly clever) approach.  A couple of functions that then take a date and format as you wanted.

var d = new Date()
alert(fmtdate(d))

function fmtdate(d) {
    return d.getFullYear()+zpad2(d.getMonth()+1)+zpad2(d.getDate())+zpad2(d.getHours())+zpad2(d.getMinutes())+zpad2(d.getSeconds())
}

function zpad2(n) {
    if (n<10) { n = ("0"+n); }
    return n;
}

Open in new window

~bp

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial