473,804 Members | 2,146 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Formatting strings

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="JavaS cript">

function ShowDateTime()
{
var today = new Date();
var mo=today.getMon th()+1;
var da=today.getDat e();
var ho=today.getHou rs();
var mi=today.getMin utes();

# 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!
--
Nige

Please replace YYYY with the current year
ille quis mortem cum maximus ludos, vincat
Jul 20 '05
26 2799
JRS: In article <71************ *************** *****@4ax.com>, seen in
news:comp.lang. javascript, Nige <uY***@ntlworld .com> posted at Thu, 6
Nov 2003 16:29:26 :-
function ShowDateTime()
{
var today = new Date();
var mo=today.getMon th()+1;
var da=today.getDat e();
var ho=today.getHou rs();
var mi=today.getMin utes();

# 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));
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #11
HikksNotAtHome wrote:
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*

Jul 20 '05 #12
Nige wrote:
In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
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.


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="JavaS cript">
<!--
function getReferenceNum ber()
{
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="' + getReferenceNum ber() + '">');
//-->
</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.getEle ment...By...(.. .) and HTMLElement.app endChild(...) 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

Jul 20 '05 #13
In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
Time zones don't enter into it, all users are in the UK.

I wonder how you can be sure.


Because it is a campaign site for broadband in Kent.
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?


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.locati on
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!
--
Nige

Please replace YYYY with the current year
ille quis mortem cum maximus ludos, vincat
Jul 20 '05 #14
In comp.lang.javas cript, Nige wrote:
My only problem now is how to extract this from the document.locati on
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!
--
Nige

Please replace YYYY with the current year
ille quis mortem cum maximus ludos, vincat
Jul 20 '05 #15
Nige wrote:
In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
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?


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.locati on
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

Jul 20 '05 #16
Nige wrote:
Cracked it! My JS book (O'Reilly) implies that window.location returns a
string, but it doesn't!


(window.)locati on 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

Jul 20 '05 #17
Thomas 'PointedEars' Lahn <Po*********@we b.de> writes:
(window.)locati on 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.prototyp e (e.g., charAt), and its typeof is "object".

If you convert it to a string, either with String(location ),
location.toStri ng() 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.valueO f method is the same
as the location.toStri ng.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #18
Lasse Reichstein Nielsen wrote:
Thomas 'PointedEars' Lahn <Po*********@we b.de> writes:
(window.)locati on 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.prototyp e (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.toStri ng() 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/.../location.html

As a curiosity, in Opera 7 the location.valueO f method is the same
as the location.toStri ng.


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

Jul 20 '05 #19
Thomas 'PointedEars' Lahn <Po*********@we b.de> writes:
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.
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/.../location.html


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.
As a curiosity, in Opera 7 the location.valueO f method is the same
as the location.toStri ng.


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.toStri ng == location.valueO f
and
location.valueO f.toString()
gives
---
function toString() {
[native code]
}
---

/L
[1] I know Netscape 4 and Mozilla have ways to make getters and setters
for properties, but that is not portable Javascript.
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
1651
by: Steve Holden | last post by:
I was messing about with formatting and realized that the right kind of object could quite easily tell me exactly what accesses are made to the mapping in a string % mapping operation. This is a fairly well-known technique, modified to tell me what keys would need to be present in any mapping used with the format. class Everything: def __init__(self, format="%s", discover=False): self.names = {} self.values =
3
5940
by: Jouke Langhout | last post by:
Hello all! For quite some time now, I've got the following problem: Access won't close properly when a user closes the application. An ACCESS process stays active and that process can only be terminated by pressing ++ and then terminate the process. I searched the entire internet and found out that there could be two things wrong (both of them are mentioned in the bug list on the access
7
3944
by: BBFrost | last post by:
I'm receiving decimal values from database queries and placing them on a report page. The users want to see the following .... Db Value Display Value 123.3400 123.34 123.0000 123 i.e. I want to trim trailing zeros and (decimal point if no decimal values
4
4028
by: Robert Manookian | last post by:
How do you format strings? i.e. In VB6: Format("AB34567", "@@@@@-@@") = "AB345-67" In .Net: ????????
2
2273
by: David Veeneman | last post by:
How does one format a date column in a GridView control? I had assumed that the DataFormat string would do it, but MSDN only shows numeric formatting codes. Can dates be formatted using that property, or is it done some other way? Thanks in advance. -- David Veeneman Foresight Systems
4
2933
by: Peter Newman | last post by:
the data input app im writing has some 30 + input fields and i want to be able to format them. I know i can use the .validate on each textbox and format the 'string' however this require loads of repetitive codeing. Is there a way possible to globally format the textboxes both on the .validate function, as well as when the enter key is pressed. Any suggestions or examples wouldbe very usefull, as i have a loads of these data forms...
11
5006
by: Dustan | last post by:
Is there any builtin function or module with a function similar to my made-up, not-written deformat function as follows? I can't imagine it would be too easy to write, but possible... 'I am coding, and he coded last week.' ('coding', 'coded', 'week') expanded (for better visual): ('coding', 'coded', 'week')
9
2324
by: john coltrane | last post by:
Is there way to create a formatted string in a similar that is similar to sprintf? The same for printing, printf? C,D,E,F,G,N,X for currency, decimal, exponential, fixed, general, numerical, and hex but these do not seem to allow for specifying the number of decimals, left/right placement, or string formatting. Thanks
6
4609
by: Tomasz J | last post by:
Hello developers, I bind my TextBox control specyfying a format stored in my application global ApplicationContext object - it has a static string CurrencyFormat property. The problem - this works fine: Text='<%# Eval("Price", ApplicationContext.CurrencyFormat) %>'
2
1608
by: Jean-Paul Calderone | last post by:
On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey <rcdailey@gmail.comwrote: mystring = ( "This is a very long string that " "spans multiple lines and does " "not include line breaks or tabs " "from the source file between " "the strings partitions.") Jean-Paul
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10603
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9176
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3836
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3003
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.