Solved

Fill text 0

Posted on 2014-07-26
7
149 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
ID: 40221796
$(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
ID: 40221836
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
ID: 40221845
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 58

Expert Comment

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

Expert Comment

by:duncanb7
ID: 40221956
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
ID: 40221964
Seriously Duncan - 100+ lines of javascript to add a 0 to a number!
0
 
LVL 13

Expert Comment

by:duncanb7
ID: 40222131
Dear Author,

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

Duncan
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Javascript closure 1 36
Full Screen problem when auto scale IFRAME 2 65
Redirect Website for Mobile Devises 7 40
Sorting a string 1 17
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)

863 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

26 Experts available now in Live!

Get 1:1 Help Now