Formatting strings

N

Nige

I'm a complete novice to JS. I want to insert the date and time into a
document in the format:

WB-MMDDHHmm

Where:

WB- is a fixed string prefix (the whole string is a reference number)
MM is the month 01 to 12, with a leading 0 if required
DD is the day 01 to 31, with a leading 0 if required
HH is the hour 00 to 23, with a leading 0 if required
mm is the minute 00 to 59, with a leading 0 if required


I've got this far:


<script language="JavaScript">

function ShowDateTime()
{
var today = new Date();
var mo=today.getMonth()+1;
var da=today.getDate();
var ho=today.getHours();
var mi=today.getMinutes();

# parse here #

document.write("WB-"+mo+da+ho+mi);
}

</script>


The problem is the bit to parse the strings, I've tried

if (mo.length < 2) mo="0"+mo; ... etc

but it doesn't work.

Help!
 
T

Thomas 'PointedEars' Lahn

Nige said:
function ShowDateTime()
{
var today = new Date();
var mo=today.getMonth()+1;
var da=today.getDate();
var ho=today.getHours();
var mi=today.getMinutes();

# parse here #

document.write("WB-"+mo+da+ho+mi);
}
[...]

The problem is the bit to parse the strings, I've tried

if (mo.length < 2) mo="0"+mo; ... etc

but it doesn't work.

The Date.get...(...) methods return values of type `number'. When you assign
them to a variable and use the lookup operator `.' with that variable, the
value stored in that variable is converted to a Number object.
Unfortunately, those objects do not have a `length' property, so the value
is `undefined'. But `undefined < 2' equals `false' (as you can and should
test with alert(...) or document.write(...)) so the second assignment to
`mo' aso. is not executed.

I see two possible approaches to solve the problem:

A) Convert the number into a string. String objects have a
length property you can compare with:

if (String(mo).length < 2)
...

B) What you need is only the leading zero for a two-digit number.
So concatenate it only when it is needed, as the number is less
than 10:

if (mo < 10)
...

I use and recommend to use B) since it is faster and allocates less memory.


HTH

PointedEars
 
N

Nige

In said:
The Date.get...(...) methods return values of type `number'.

Of course, thank you.

I've since realized that the problem is more complex than I thought. The
plan was to generate a reference number consisting of the date and time
when a user submits a form.

The reference number is created by the CGI script that processes the
form, but (of course) if the user's clock is not the same as the server
then the numbers are different. D'OH!

Is there a way to generate a string referencing the current date and
time (as MMDDHHmm) when a user presses the Submit button, send this
string with the other form data, then display this string on the page
that is displayed next?
 
T

Thomas 'PointedEars' Lahn

Nige said:
I've since realized that the problem is more complex than I thought. The
plan was to generate a reference number consisting of the date and time
when a user submits a form.

The reference number is created by the CGI script that processes the
form, but (of course) if the user's clock is not the same as the server
then the numbers are different. D'OH!

Null problemo. You should never use client-side data when server-side data
is more reliable. Did you think of timezones and stuff like that? Use the
server time for generating the reference number which also frees you from
dependence of client-side JavaScript support and unreliable techniques (like
changing the value of an `input' element on submit which could, but should
not be done here.)


PointedEars

P.S.
Please don't change the Subject unless there is really a change of subject.
 
N

Nige

In said:
You should never use client-side data when server-side data
is more reliable.

Time zones don't enter into it, all users are in the UK. All I really
need is a reference number that gives the date and approx time, it
doesn't even have to be unique, but the user must be shown the same
number that I get sent by the CGI.

As I said in my other post (which I sent without giving full details,
sorry), I can't send the CGI data to the next page. So the simple option
(assuming it is simple) is the generate a string on the form page, send
it with the CGI data, and display it on the following page.

Can it be done?
 
T

Thomas 'PointedEars' Lahn

Nige said:
I don't know how to make the CGI script send a value to the next page.

This is off-topic here (since it has nothing to do with JavaScript)
but what kind of CGI script are you talking about?


PointedEars

P.S.
Don't expect people to manipulate the `To' when they send you e-mail.
 
T

Thomas 'PointedEars' Lahn

HikksNotAtHome said:
Server Side Javascript potentially running as a CGI is off-topic in a
Javascript newsgroup?

Of course not, but nothing was said about server-side JavaScript and I
assumed that the OP did not wrote about server-side JavaScript because
he distiguished CGI from that (which is incorrect, though.)
Dont try to email people from a group and its a non-issue. Post to news, get
answered in news, and theres no problem.

Usenet is public newsgroups *and* private (e-)mail (PM), at least because
it is obvious that some things do not belong into newsgroups but are better
to be written via e-mail than not written at all (as the Netiquette
recommends.) I'm sorry for you that you are not aware of this, but that
is your problem, not mine.


EOD

PointedEars
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
function ShowDateTime()
{
var today = new Date();
var mo=today.getMonth()+1;
var da=today.getDate();
var ho=today.getHours();
var mi=today.getMinutes();

# parse here #

document.write("WB-"+mo+da+ho+mi);

The problem is the bit to parse the strings,


Perhaps you have not read _all_ that the FAQ has to say; see signature
below.

You do not want to parse them, but to format them

function LZ(x) {return(x<0||x>9?"":"0")+x} // add leading 0

document.write("WB-" + LZ(mo) + LZ(da) + LZ(ho) + LZ(mi));
 
T

Thomas 'PointedEars' Lahn

HikksNotAtHome said:
I have no problem with it. I dont recieve the mails (If I do, they get
deleted), so I fail to see how Usenet is a "private" place. As I said, don't
try to email someone, no problems. Trying to get outside of the public Usenet
into private Email is crossing a boundary that I don't care to cross. It opens
up too many problems. If the "Netiquette" says its ok, I don't care, I don't do
it and I won't do it.

*PLONK*
 
T

Thomas 'PointedEars' Lahn

Nige said:
Time zones don't enter into it, all users are in the UK.

I wonder how you can be sure.
All I really need is a reference number that gives the date and approx
time, it doesn't even have to be unique, but the user must be shown the
same number that I get sent by the CGI.

Why, you don't need JavaScript for this (unless your CGI application uses
server-side JavaScript.) Let the CGI application generate the reference
number. Here is it in PHP (untested):

<input type="text" value="<?php
echo date('mdHi', time());
?>">
As I said in my other post (which I sent without giving full details,
sorry), I can't send the CGI data to the next page.

Could you please explain why you assume this is the case?
So the simple option (assuming it is simple) is the generate a string
on the form page, send it with the CGI data, and display it on the
following page.

I think the problem is that we mean different things by "CGI data".
However, as written before, use

<input type="hidden" value="">

and manipulate the value on submit. But the user will then not *see* what
the reference number is, at least not in the form, since it is generated
on submit and not on form generation/display. If you want to the latter
*and* a client-side solution, you need to write the `input' element
dynamically, while using `text' for the value of its `type' attribute:

<script type="text/javascript" language="JavaScript">
<!--
function getReferenceNumber()
{
var
d = new Date(),
iMonth = d.getMonth() + 1,
iDay = d.getDay(),
iHours = d.getHours(),
iMins = d.getMinutes();

return (
(iMonth < 10 ? "0" : "") + iMonth
+ (iDay < 10 ? "0" : "") + iDay
+ (iHours < 10 ? "0" : "") + iHours
+ (iMins < 10 ? "0" : "") + iMins)
}

document.write(
'<input type="text" value="' + getReferenceNumber() + '">');
//-->
</script>

The use of document.write(...) depends on the document type: In XHTML,
AFAIK you are required to use the W3C-DOM, with its
document.getElement...By...(...) and HTMLElement.appendChild(...) methods,
instead.

You could also fill the `input' element onload of the `body' element, giving
it a name and referencing it with document.forms[...].elements[...]'. But
users without JavaScript will then see an empty `input' element if you do
not specify otherwise.
Can it be done?

Yes, but if you choose the client-side solution and the users (customers?)
have their JavaScript disabled or no JavaScript support at all, you will
get no (useful) reference number at all. Dependence upon client-side
JavaScript is a Bad Thing, unless we are talking about an Intranet with
client-side conditions under your control or documents that cannot be
reached other than with JavaScript support (which can be evil[tm], too!)


HTH

PointedEars
 
N

Nige

In said:
I wonder how you can be sure.

Because it is a campaign site for broadband in Kent.
Could you please explain why you assume this is the case?

I've since discovered that I *can* send the date to the page, by
following the url with a ? then the server created date string.

My only problem now is how to extract this from the document.location
property (it is there). I've tried code the parse the string to write
the last 8 digits, and code to find the "?" and write the remainder.

I think I need to have a break!
 
N

Nige

My only problem now is how to extract this from the document.location
property (it is there). I've tried code the parse the string to write
the last 8 digits, and code to find the "?" and write the remainder.

I think I need to have a break!

Cracked it! My JS book (O'Reilly) implies that window.location returns a
string, but it doesn't!
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
I have no problem with it. I dont recieve the mails (If I do, they get
deleted), so I fail to see how Usenet is a "private" place. As I said, don't
try to email someone, no problems. Trying to get outside of the public Usenet
into private Email is crossing a boundary that I don't care to cross. It opens
up too many problems. If the "Netiquette" says its ok, I don't care, I don't do
it and I won't do it.


It is possible that AOL may have problems with it; certainly they
should. If Mr. H Ikksnot gets a couple of AOL accounts, one for use at
work and the other at home, he may be disgruntled to receive your spam.

One should not use an address that may cause mail to be directed to an
account, extant or otherwise, that one does not have positive permission
to use.

Different providers, however, do actually state different, or no,
conditions; presumably depending on a combination of their corporate
intelligence and public-spiritedness.

It is possible that AOL may have created, or be willing to create, some
range or ranges of left parts that will not be allowed for customers and
can therefore be offered for your purpose; they would then probably
arrange to bounce or dump all messages to that range efficiently.
 
T

Thomas 'PointedEars' Lahn

Nige said:
I've since discovered that I *can* send the date to the page, by
following the url with a ? then the server created date string.

Yes, that is called a HTTP GET request which
is also the default for submitting a form.
My only problem now is how to extract this from the document.location
property (it is there). I've tried code the parse the string to write
the last 8 digits, and code to find the "?" and write the remainder.

That has nothing to do with CGI as you have told before!
However, I have written a prototype that can be useful here:

http://pointedears.de.vu/scripts/search.htm

Note that the documentation is a bit out of date (see the source code in the
..js file.) `TValue' was changed to `Value', `TSearchStr' to `SearchString',
and enhanced.js is now deprecated; use string.js instead. (Please also
excuse that I wrote `class' in the comments in those days -- it'll be
changed :)).


PointedEars
 
T

Thomas 'PointedEars' Lahn

Nige said:
Cracked it! My JS book (O'Reilly) implies that window.location returns a
string, but it doesn't!

(window.)location is in recent user agents a string value *and* an
object with properties like `href', `protocol', `path', `hash' aso.

Here, in Mozilla/5.0 rv:1.5 and IE 6.0 SP-1, it is. Which user-agent
are you testing with?


PointedEars
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
(window.)location is in recent user agents a string value *and* an
object with properties like `href', `protocol', `path', `hash' aso.
Here, in Mozilla/5.0 rv:1.5 and IE 6.0 SP-1, it is. Which user-agent
are you testing with?

In my IE6, it is only an object. It doesn't have the methods from
String.prototype (e.g., charAt), and its typeof is "object".

If you convert it to a string, either with String(location),
location.toString() or ""+location, the resulting string contains
the URL, but that just means that it can be converted to a string.

There is some magic to the location object, though, since *assigning*
to it will really assign to location.href.

As a curiosity, in Opera 7 the location.valueOf method is the same
as the location.toString.

/L
 
T

Thomas 'PointedEars' Lahn

Lasse said:
In my IE6, it is only an object. It doesn't have the methods from
String.prototype (e.g., charAt), and its typeof is "object".

You're right, the same goes for my UAs. What I meant was that
it returns also a URI string (due to its toString() method) in
the right context.

In contrast, in older UAs like Opera 6 (IIRC), `location' stores
only a primitive string value.
If you convert it to a string, either with String(location),
location.toString() or ""+location, the resulting string contains
the URL, but that just means that it can be converted to a string.
ACK

There is some magic to the location object, though, since *assigning*
to it will really assign to location.href.

There is no magic involved :) See
http://devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/location.html

As a curiosity, in Opera 7 the location.valueOf method is the same
as the location.toString.

Same in Mozilla/5.0 and IE 6.0 SP-1, as expected.


PointedEars
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
In contrast, in older UAs like Opera 6 (IIRC), `location' stores
only a primitive string value.

YRI (You Remember Incorrectly :)
In Opera 4, 5 and 6, location is an object. I don't have Opera 3 installed,
and Opera 2 doesn't support Javascript.

The same goes for Netscape 4 and 3. You have to go back to Netscape 2
to find a location property that is a plain string.

Tha qualified as "magic" to me (something that depends on internal
code and cannot be implemented by a Javscript programmer, like the
array length property [1]).

It says:
---
If you assign a string to the location property of an object,
JavaScript creates a location object and assigns that string to its
href property.
---
That is not correct for *any* object. The following gives me "string":
---
var x = {}; // or var x=document.body;
x.location = "foo";
typeof x.location
---
So, it is only for window objects, not any object.
Same in Mozilla/5.0 and IE 6.0 SP-1, as expected.

In my IE 6, the location object doesn't have a valueOf property.
What I mean is that in Opera is the *exact* same function, it doesn't
just give the same result. That is:
location.toString == location.valueOf
and
location.valueOf.toString()
gives
 
T

Thomas 'PointedEars' Lahn

Lasse said:
YRI (You Remember Incorrectly :)

Having just installed Opera 6.0 again [1], I realize that you are both
right *and* wrong! :)

I remembered correctly, *but* my testing method was in fact flawed:
From the fact that Opera's `location' shows no properties when iterating
through them with `for (var p in location)', I falsely concluded that it
has none and is therefore no object at all.[2] But as you wrote, it is of
type `object' and has at least `href', `search' and `protocol' properties
(when I think about it, Opera won't have distributed this much if it had not.)

Because you cannot rely on what iteration shows, is there a way to get
all properties of an object other than brute force, and if that, how it
is done?
In Opera 4, 5 and 6, location is an object.

It is in v6, and most certainly is in v4 and v5.
I don't have Opera 3 installed,

See [1].
The same goes for Netscape 4 and 3.
ACK


Tha qualified as "magic" to me (something that depends on internal
code and cannot be implemented by a Javscript programmer,

OK. I don't consider things described in specifications "magic".

It also says:

| The location object is contained by the window object and is within its
| scope. If you refer to a location object without specifying a window, the
| location object represents the current location. If you refer to a
| location object and specify a window name, as in windowReference.location,
| the location object represents the location of the specified window.

and BTW, your `x' is not a Location object.
In my IE 6, the location object doesn't have a valueOf property.

Oops! Me too. Debug bug. System halted.


PointedEars
___________
[1] <http://arc.opera.com/pub/opera/>
[2] <http://pointedears.de.vu/scripts/test/location.html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top