TonalDev
TonalDev

Reputation: 583

Customize javascript Date

I have a simple code that echos the current Hour+Minute+Date as one number sequence.

I need to add 1 to all the numbers outputted, individually.

Example: If the current time and date is: 22321512 then i need jQuery to output: 33432623.

My knowledge in jQuery is pretty slim, How can this be achieved?

HTML:

<span id="date"></span>

Code:

var now = dateFormat(new Date(), "HHMMddmm");
$('#date').append(now);

Upvotes: 0

Views: 64

Answers (3)

pete
pete

Reputation: 25081

If you want to merely increment each unit by 1 and let the JavaScript engine advance the date and time on overflow, then Captain John's answer will work perfectly. This means that, for example, if this routine were to be run at 11:59 PM on December 31, your output would be 00000100.

If you want each unit to be incremented by 1 without the date being advanced, you will have to stop relying on Steven Levithan's [excellent] dateFormat library and do it yourself:

var now = new Date(),
    hours = now.getHours() + 1,     // add 1 hour
    minutes = now.getMinutes() + 1, // add 1 minute
    date = now.getDate() + 1,       // add 1 day
    month = now.getMonth() + 1,     // add 1 month
    padLeft = function (val) {      // make a formatter
        while (val.length < 2) {
            val = '0' + val;        // string is less than 2 characters, pad left side with '0'
        }
        return val;                 // return formatted string
    },
    formatted = padLeft(hours) + padLeft(minutes) + padLeft(date) + padLeft(month);
$('#date').append(formatted);

Upvotes: 1

Pedro Moreira
Pedro Moreira

Reputation: 965

Getting number length as string you can easily sum 1 to each number.

  • The result is given as timestamp
  • To get Date object, use new Date(result);

    var now = new Date().getTime(); // 22321512 on your example

    // Answer var result = 0; var str = now.toString(); for(var i = 0; i < str.length; i++) { result += Math.pow(10, i); } result += now; // Ex.: 22321512 + 11111111

Upvotes: 0

Captain John
Captain John

Reputation: 1891

You need to do the following roughly:

var currentDate = new Date();
var myDate = new Date(currentDate.getYear() + 1, currentDate.getMonth() + 1, currentDate.getDay() + 1);

alert(myDate.getTime());

Should solve your problem.

Upvotes: 2

Related Questions