Solved

Fill text 0

Posted on 2014-07-26
7
146 Views
Last Modified: 2014-08-27
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
0
Comment
Question by:tonelm54
  • 3
  • 2
  • 2
7 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
$(this).val(year + "/" + addzero(month) + "/" + addzero(day) + " " + addzero(hours) + ":" + minutes + ":" + seconds);

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

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 58

Expert Comment

by:Gary
Comment Utility
Ray is correct about js months starting from 0 to 11
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Seriously Duncan - 100+ lines of javascript to add a 0 to a number!
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
Dear Author,

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

Duncan
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now