473,320 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How to convert datetime format using Javascript

Dear all

In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.

Please give me some advices.

Cheers
Bon

Aug 3 '06 #1
10 162589

bo***********@gmail.com wrote:
Dear all

In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.
You can try using a date object:

new Date('dd/mm/yyyy');

however on my system 12/02/2005 always returns 2-Dec-2005 regardless of
how I set my system or browser date format preferences. It seems the
absurd US date system is all pervasive.

If you do not provide a time, the above conversion of string to date
object will always return 00:00:00 (at least on the systems/browsers I
tested). Given the vaguaries of how the string will be interpreted if
converted to a date object, and the fact that the time seems to be
irrelevant, you might as well just use string manipulation:

<form action="">
Date (dd/mm/yyyy) <input type="text" name="val1" size="30"
value="12/02/1005"><br>
<input type="button" value="test"
onclick="
var dateBits = this.form.val1.value.split('/');
alert(dateBits[2] + '-' + dateBits[1]
+ '-' + dateBits[0] + ' 00:00:00');
">
</form>
You might want to validate the input, add leading zeros, etc.
--
Rob

Aug 3 '06 #2

<bo***********@gmail.comwrote in message
news:11*********************@75g2000cwc.googlegrou ps.com...
Dear all

In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.

Please give me some advices.
Assuming that the date format as dd/mm/yyyy you can easily convert it to a
date by splitting it into date parts:

myDateParts = myDate.split("/");

You can then build a new date from the parts like so:

myJSDate = new Date(myDateParts[2], myDateParts[1], myDateParts[0]);

It should be clear that you could also just output the date as you want it
using the same array but I always prefer generating a real date. Note that
you're not specifying a time so time will always be "00:00:00".

Once you have a date you can output it however you like. To make that
easier I've a date extensions library that might help:

http://www.depressedpress.com/Conten...ions/Index.cfm

Part of this is are "dateFormat()" and "timeFormat()" methods. You can use
them to output the format you want like so:

myJSDate.formatDate("yyyy-mm-dd") + " " + myJSDate.timeFormat("hh:mm:ss")

The library is large and if you're just looking for a one-off then it's
almost definately overkill, but if you want the freedom to change the format
at whim then it makes things very easy.

Jim Davis
Aug 3 '06 #3
Jim Davis wrote:
Once you have a date you can output it however you like. To make that
easier I've a date extensions library that might help:
http://www.depressedpress.com/Conten...ions/Index.cfm
Similarly,
http://www.javascripttoolbox.com/lib/date/

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 3 '06 #4

Jim Davis wrote:
<bo***********@gmail.comwrote in message
news:11*********************@75g2000cwc.googlegrou ps.com...
Dear all

In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.

Please give me some advices.

Assuming that the date format as dd/mm/yyyy you can easily convert it to a
date by splitting it into date parts:

myDateParts = myDate.split("/");

You can then build a new date from the parts like so:

myJSDate = new Date(myDateParts[2], myDateParts[1], myDateParts[0]);
Except that the month number starts at zero, so the above will be out
by 1 month. Subtract 1 from the month number:

myJSDate = new Date(myDateParts[2], myDateParts[1] - 1,
myDateParts[0]);

It should be clear that you could also just output the date as you want it
using the same array but I always prefer generating a real date. Note that
you're not specifying a time so time will always be "00:00:00".
Except that it appears to be unnecessary and may introduce a complexity
that isn't required (two easy mistakes are in this thread already).
What is the benefit of using a date object when all that is required is
re-formatting a string?

[...]
--
Rob

Aug 3 '06 #5
JRS: In article <11**********************@p79g2000cwp.googlegroups .com>
, dated Thu, 3 Aug 2006 03:44:04 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auposted :
new Date('dd/mm/yyyy');
>If you do not provide a time, the above conversion of string to date
object will always return 00:00:00 (at least on the systems/browsers I
tested).
Strictly speaking, never, since that code creates a Date Object which
holds an IEEE Double of GMT milliseconds rather than a String. It is
the toString method of the Date Object (maybe called implicitly) or the
other non-UTC methods which are responsible for the "00:00:00"; and the
UTC methods will generally give a different result.

If the date in question is the last Sunday of March or October, and the
system is set for an EU location in the time zone West of Greenwich (the
Azores and South-East Greenland), then I'd be reluctant to predict the
result.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/- see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Aug 3 '06 #6
JRS: In article <11*********************@75g2000cwc.googlegroups.c om>,
dated Thu, 3 Aug 2006 03:07:57 remote, seen in
news:comp.lang.javascript, bo***********@gmail.com posted :
>
In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.

Please give me some advices.
Before asking a question, one should read the frequently-cited newsgroup
FAQ. It contains the words "date" "dates" "time" "times" in Section 3.

If you mean exactly what you have written above, then all you need is
indicated by
St = "03/08/2006"
St = St.replace(/(\d\d).(\d\d).(\d\d\d\d)/, "$3-£2-$1 00:00:00")
// 2006-08-03 00:00:00
Given that your users can handle dd/mm/yyyy, I assume that they are too
intelligent to use the 12-hour clock for data.
If you want to read that format into a Date Object,
D = new Date(St.replace(/(\d\d).(\d\d).(\d\d\d\d)/, "$3/$2/$1"))
should always work though not guaranteed by ECMA spec; and the following
is so guaranteed.
M = St.match(/(\d\d).(\d\d).(\d\d\d\d)/)
D = new Date(M[3], M[2]-1, M[1])

( Alternatively, consider
D = new Date(St.split('/').reverse().join('/'))
and note that JD's method using split will, coded as shown, give the
corresponding date in the following month. I test my code. )
If the input is not GUARANTEED ##/##/####, then M should be checked for
not null before the D line.

If the input may be an invalid date such as 01/17/2006, then validate it
as via sig line 3 below.

If you want to output a Date Object in ISO format, then add & use Method
ISOlocalDTstr, or use it to guide the creation of a function.
The above uses a Date Object representing the input as a local date.
Extended organisations should consider the use of UTC/GMT. The UTC
Methods of Date Objects are much faster than the local ones.

Read the newsgroup FAQ.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 3 '06 #7

"Dr John Stockton" <jr*@merlyn.demon.co.ukwrote in message
news:C+**************@merlyn.demon.co.uk...
>snip<
( Alternatively, consider
D = new Date(St.split('/').reverse().join('/'))
and note that JD's method using split will, coded as shown, give the
corresponding date in the following month. I test my code. )
Well, John - that's what makes you special!

Thanks (to both you and Rob) for catching the error and keeping me honest.

Jim Davis
Aug 4 '06 #8
"RobG" <rg***@iinet.net.auwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
>
Jim Davis wrote:
>snip<
It should be clear that you could also just output the date as you want
it
using the same array but I always prefer generating a real date. Note
that
you're not specifying a time so time will always be "00:00:00".

Except that it appears to be unnecessary and may introduce a complexity
that isn't required (two easy mistakes are in this thread already).
What is the benefit of using a date object when all that is required is
re-formatting a string?
In this case (from what I've assumed) there's a form that accepts a date.
That date is then presented in a different format later. You could, of
course (as I said originally) just output the date as you like without
conversion to a "real" date object. Then, to change either the input format
or the output format you have to change both aspects of the code.

In general I like to reduce dependencies between the input and eventual
output.

I would prefer to convert the input to an abstracted Date object as soon as
possible and then format that abstraction for presentation. My presentation
code would expect a Date and my input code would result in a Date. The
presentation can change without affecting the input and the input can change
without affecting the presentation.

I find that this often reduces overall complexity: I don't need to maintain
knowledge of a format throughout the larger process. Instead I have smaller
chunks of code which may, in and of themselves, be slightly more complex
than the corrosponding alternatives but when taken as a whole simply the
interaction between components.

At the very least I find the resulting code much more portable and
versatile. In general the additional coding required is minimal and saves
you time later when things invariably change.

Of course that's only my preference.

Jim Davis
Aug 4 '06 #9
JRS: In article <yJ******************************@giganews.com>, dated
Thu, 3 Aug 2006 11:06:49 remote, seen in news:comp.lang.javascript, Jim
Davis <ne********@vboston.composted :
>Part of this is are "dateFormat()" and "timeFormat()" methods. You can use
them to output the format you want like so:

myJSDate.formatDate("yyyy-mm-dd") + " " + myJSDate.timeFormat("hh:mm:ss")
Would it not be better if the format methods allowed spaces in their
argument strings? It would then not be necessary to use the middle
string above.

Suggestion : any alphabetic "word" will be interpreted either as a
recognised component or as an error; any non-alphanumeric will be taken
as a literal to be copied; decimal digits need further thought; there
could be an escape character.

Read the newsgroup FAQ.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 4 '06 #10

"Dr John Stockton" <jr*@merlyn.demon.co.ukwrote in message
news:j7**************@merlyn.demon.co.uk...
JRS: In article <yJ******************************@giganews.com>, dated
Thu, 3 Aug 2006 11:06:49 remote, seen in news:comp.lang.javascript, Jim
Davis <ne********@vboston.composted :
>>Part of this is are "dateFormat()" and "timeFormat()" methods. You can
use
them to output the format you want like so:

myJSDate.formatDate("yyyy-mm-dd") + " " + myJSDate.timeFormat("hh:mm:ss")

Would it not be better if the format methods allowed spaces in their
argument strings? It would then not be necessary to use the middle
string above.
For what it's worth you can pass spaces to the function. The middle string
in the example isn't really needed, this would work as well (although I also
apparently inverted the name of the dateFormat() function -damn that was a
bad morning):

myJSDate.dateFormat("yyyy-mm-dd ") + myJSDate.timeFormat("hh:mm:ss")

Although that would result in the same thing the extra space can easily be
"lost" visually - I'd probably still add the connecting string.

I can see the argument for combining them.

There is a minor point that the mask characters would have to change since
the two functions share characters, but that wouldn't be all that hard.

In this case they were originally written to mirror the ColdFusion
"TimeFormat()" and "DateFormat()" functions (the mask characters are the
same although there are few minor additions).

I guess I've just become so used to using the CF functions that it seems odd
to me to combine them.

Jim Davis

Aug 5 '06 #11

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

Similar topics

1
by: Li Weng | last post by:
Hi, When I retrieve urn:schemas:httpmail:date field, how do I set the format from VB.net code? I assume I should have several DateTime formats to choose from. Or is there any VB.net class to...
2
by: Grey | last post by:
I use the DateTime format to change the date format, i.e. string a = "21/02/2004"; Convert.ToDateTime(a).ToString("MMMM dd, yyyy"); These two lines work well in my VS.NET development machine. But...
2
by: ziggislaw | last post by:
hello how can I convert DateTime from "25.12.2005" to "2005-12-25 00:00:00.000" ? Now I have DateTime as string (I get it from <asp:label>). Thanks
5
by: dubing | last post by:
Hello everyone, There is a field of DATETIME type in our Access 2000 database. PHP is used to query the data and display the query results on the web. Does Access provide any function that can...
4
by: kanthi84 | last post by:
Hi i would like to know, how to retrieve data stored as blob in database in the format required for displaying. one suggestion i got was of using poi package. i would like to know whether it is...
2
by: joyjignesh | last post by:
hi i have make a report with mshflexgrid. the report between two date. when i have written query .open"select * from tablename where t_date>=convert(datetime,' " & text1.text &"') and ...
4
by: thomasc1020 | last post by:
This is regarding VB.NET 2003. Variable 'Date' is a string and it contains date information in this format: "DEC/05/2007". Now I am trying to convert the format as "2007-12-05". Is it...
3
by: huohaodian | last post by:
Hi, How can I convert a value created from DateTime.Now() to the datetime format that SQL Server recognises? Thanks in advance.
2
by: sunita jadhav | last post by:
How can i mask the date format for all types of date format in a single function using javascript
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.