Why is this Javascript script not giving ant output?

I want to create a simple date counter that will output in html where the script is in the file. Here's a JSFiddle, and here's what the script is:

var today = newDate();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();

if (dd = 1 || 21 || 31) {
    dd = dd + 'st'
} else if (dd = 2 || 22) {
    dd = dd + 'nd'
} else if (dd = 3 || 23) {
    dd = dd + 'nd'
} else {
    dd = dd + 'th'
}

if (mm = 0) {
    mm = "JANUARY";
} else if (mm = 1) {
    mm = "FEBRUARY";
} else if (mm = 2) {
    mm = "MARCH";
} else if (mm = 3) {
    mm = "APRIL";
} else if (mm = 4) {
    mm = "MAY";
} else if (mm = 5) {
    mm = "JUNE";
} else if (mm = 6) {
    mm = "JULY";
} else if (mm = 7) {
    mm = "AUGUST";
} else if (mm = 8) {
    mm = "SEPTEMBER";
} else if (mm = 9) {
    mm = "OCTOBER";
} else if (mm = 10) {
    mm = "NOVEMBER";
} else {
    mm = "DECEMBER";
}

today = dd + '|' + mm + '|' + yyyy;
document.write(today);

      

I know this is the most inefficient and possibly the wrong way to write code in general (this is the second thing I've ever done in JS.), But please accept my silly mistakes.

Many thanks.

-2


source to share


4 answers


Avoid cascading if

var month = ["January", "Feb", "March",....,"Dec"];//store array of months as string
var suffix =["st","nd","rd","th"];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
var op="";
if(parseInt(dd) > 4)
    op+=dd+""+suffix[3]+"|";
else
    op+=dd+""+suffix[(parseInt(dd)%10)-1]+"|";
op+=month[parseInt(mm)]+"|"+yyyy;

      



Make it just a working violin

FYI: We have now seen the answer and 0-11 for months while 0 represents Jan and 11 represents Dec

0


source


Using

var today = new Date();

      

instead

var today = newDate();

      

And the output will be "1st | FEBRUARY | 2015"




Update: (more elegant way)

b=(new Date()).toLocaleString('en-us', {
  day: 'numeric',
  month: "long",
  year: 'numeric'
}).replace(/(\w+) (\d+), (\d+)/, '$2|$1|$3'); // 30|June|2015
dd=parseInt(b, 10);
op='';
suffix =["st","nd","rd","th"];
if(parseInt(dd) > 4)
    op=dd+""+suffix[3];
else
    op=dd+""+suffix[(parseInt(dd)%10)-1];
alert(b.replace(/^\d+/, op))
      

Run codeHide result


+1


source


just write: var today = new Date();

0


source


Don't reinvent the wheel, just use moment.js :

var d = new Date();

document.write(moment().format('Do|MMMM|YYYY'));
      

<script src="https://raw.githubusercontent.com/moment/moment/develop/moment.js"></script>
      

Run codeHide result


0


source







All Articles