Fill text 0

Is it possible to fill a variable with left 0s? For example 9 to make as 09?

I know in excel you can use text("00","09") which would return "09", or just "12" if you tried text("00","12").

Im trying to format current time, so Ive currently got:-
        $('.clickToTime').click(function () {
            var currentTime = new Date();
       
            var month = currentTime.getMonth();
            var day = currentTime.getDate();
            var year = currentTime.getFullYear();
            var hours = currentTime.getHours();
            var minutes = currentTime.getMinutes();
            var seconds = currentTime.getSeconds();

            $(this).val(year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds);
        });

Which works, but displays "2014/6/26 21:4:3" where I want it to display "2014/06/26 21:04:30".

Interesting enough, which I cannot figure out why is why it returns 6 instead of 7 for the month.... :-S

I know this is 2 questions, but hopefully someone is able to answer.

Thanks in advance
tonelm54Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GaryCommented:
$(this).val(year + "/" + addzero(month) + "/" + addzero(day) + " " + addzero(hours) + ":" + minutes + ":" + seconds);

function addzero(el) {
    return ("0" + el).slice(-2)
}

Open in new window

0
Ray PaseurCommented:
JavaScript (IIRC) numbers the months from zero.

You can also do something like this to get leading zeros.

	if (ss < 10) { ss = "0"+ss; }
	if (mm < 10) { mm = "0"+mm; }
	if (hh < 10) { hh = "0"+hh; }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
And this is not exactly on point, but it might be helpful to store it in your library of code samples.
http://iconoun.com/demo/client_time_verbose.php

<?php // RAY_client_time_verbose.php
error_reporting(E_ALL);
ob_start();


// USE JAVASCRIPT TO GET THE CLIENT TIME AND COMPARE TO THE SERVER TIME


// TEST WITH DIFFERENT TIMEZONES IN THE URL PARAMETER
$z = isset($_GET["z"]) ? strtoupper(substr(trim($_GET["z"]),0,1)) : "?";
switch ($z)
{
    case 'W' : date_default_timezone_set('America/Los_Angeles'); break;
    case 'M' : date_default_timezone_set('America/Denver');      break;
    case 'C' : date_default_timezone_set('America/Chicago');     break;
    case 'E' : date_default_timezone_set('America/New_York');    break;
    default  : date_default_timezone_set('UTC');
}

// MAKE IT EASIER TO READ
echo "<pre>";

// IF THE FORM IS SUBMITTED
if (!empty($_POST))
{
    // ADD A CAUTIONARY NOTE
    echo "PLEASE DO NOT 'REFRESH' THIS PAGE -- USE THE SUBMIT BUTTON INSTEAD!";

    // COMPUTE THE SERVER TIME AND DIFFERENCE FROM CLIENT POST-REQUEST
    list ($usec, $sec) = explode(' ', microtime());
    $server_time = number_format(round($sec * 1000 + $usec * 1000), 0, '', '');
    $client_time = $_POST["date_u"];
    $milli_diff  = $server_time - $client_time;

    echo "<br/>COMPUTED TIME DIFFERENCE BETWEEN SERVER AND CLIENT: $milli_diff MS";
    echo PHP_EOL;

    // ACTIVATE THIS TO SEE THE POST ARRAY
    // var_dump($_POST);

    // SERVER SECONDS SINCE THE EPOCH
    $server_timestamp = time();

    // CLIENT JAVASCRIPT MILLISECONDS SINCE THE EPOCH
    $client_millitime = $_POST["date_u"];
    $client_timestamp = (int)round($client_millitime / 1000.0);
    $timestamps_diff  = $server_timestamp - $client_timestamp;
    echo "<br/>ACCORDING TO THE VALUE FROM dateObject.getTime()";
    echo "<br/>TIME FROM CLIENT POST TO SERVER PROCESSING IS $timestamps_diff SECONDS";
    echo "<br/>CLIENT ISO8601 DATETIME IS " . date('c', $client_timestamp);
    echo PHP_EOL;

    // CLIENT'S OFFSET FROM GMT / UTC
    $client_offset_hours = (int)round($_POST["date_O"] / 60);
    echo "<br/>ACCORDING TO THE VALUE FROM dateObject.getTimezoneOffset()";
    echo "<br/>CLIENT IS LOCATED $client_offset_hours HOURS FROM UTC";
    echo PHP_EOL;

    // CLIENT'S DATE FROM THE POSTED STRINGS INTO A TIMESTAMP
    $client_timestamp = strtotime
    (       $_POST["date_Y"]
    . '-' . $_POST["date_m"]
    . '-' . $_POST["date_d"]
    . 'T' . $_POST["date_h"]
    . ':' . $_POST["date_i"]
    . ':' . $_POST["date_s"]
    )
    ;
    if ($client_timestamp === FALSE) echo "<br/>POST DATA IS BOGUS";

    echo "<br/>ACCORDING TO THE SEVERAL VALUES FROM dateObject.get***()";
    echo "<br/>CLIENT ISO8601 DATETIME IS " . date('c', $client_timestamp);
    echo "<br/>CLIENT PRETTY DATE IS " . date('l, \t\h\e jS \o\f F Y g:i:s A', $client_timestamp);
    echo PHP_EOL;
}

// CURRENT SERVER INFORMATION
echo "<br/>THE SERVER TIMEZONE IS " . date_default_timezone_get();
echo "<br/>THE SERVER DATETIME IS " . date('c');

// END OF PHP - USE HTML AND JS TO CREATE THE FORM
echo "</pre>" . PHP_EOL; ?>

<form id="d" method="post">
<input name="date_O" id="dateTime_O" type="hidden" />
<input name="date_u" id="dateTime_u" type="hidden" />
<input name="date_Y" id="dateTime_Y" type="hidden" />
<input name="date_m" id="dateTime_m" type="hidden" />
<input name="date_d" id="dateTime_d" type="hidden" />
<input name="date_h" id="dateTime_h" type="hidden" />
<input name="date_i" id="dateTime_i" type="hidden" />
<input name="date_s" id="dateTime_s" type="hidden" />
<input type="submit" value="CHECK CLIENT DATETIME" onClick="grabTime();" />
</form>

<!-- NOTE THIS WILL GIVE YOU THE VALUES AT AT SUBMIT TIME -->
<!-- MAN PAGE REF: http://www.w3schools.com/jsref/jsref_obj_date.asp -->
<script type="text/javascript">
function grabTime(){
    var dateObject = new Date();
    document.getElementById("dateTime_O").value = dateObject.getTimezoneOffset();
    document.getElementById("dateTime_u").value = dateObject.getTime();
    document.getElementById("dateTime_Y").value = dateObject.getFullYear();
    document.getElementById("dateTime_m").value = dateObject.getMonth() + 1;
    document.getElementById("dateTime_d").value = dateObject.getDate();
    document.getElementById("dateTime_h").value = dateObject.getHours();
    document.getElementById("dateTime_i").value = dateObject.getMinutes();
    document.getElementById("dateTime_s").value = dateObject.getSeconds();
}
</script>

Open in new window

HTH, ~Ray
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

GaryCommented:
Ray is correct about js months starting from 0 to 11
0
duncanb7Commented:
Dear  tonelm54,
There is free download  date format example function ,dateFormat(), at the site,
http://blog.stevenlevithan.com/archives/date-time-format, by which you can set date
format  as Numberformat /format in excel.

Hope understand your question completely.If not pls pt it out  

Duncan

you can try it as follows
 
var now = new Date();
alert(dateFormat(now, "yyyy/mm/dd hh:MM:ss"));

Open in new window

0
GaryCommented:
Seriously Duncan - 100+ lines of javascript to add a 0 to a number!
0
duncanb7Commented:
Dear Author,

the dateFormat() ,function will let you have more flexibility to use Date format as Excel and Excell VBA

Duncan
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.