473,659 Members | 2,681 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 162654

bo***********@g mail.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******** *************@7 5g2000cwc.googl egroups.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(myDatePart s[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.format Date("yyyy-mm-dd") + " " + myJSDate.timeFo rmat("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******** *************@7 5g2000cwc.googl egroups.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(myDatePart s[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(myDatePart s[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************ **********@p79g 2000cwp.googleg roups.com>
, dated Thu, 3 Aug 2006 03:44:04 remote, seen in
news:comp.lang. javascript, RobG <rg***@iinet.ne t.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.demo n.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.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************ *********@75g20 00cwc.googlegro ups.com>,
dated Thu, 3 Aug 2006 03:07:57 remote, seen in
news:comp.lang. javascript, bo***********@g mail.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().jo in('/'))
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.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 3 '06 #7

"Dr John Stockton" <jr*@merlyn.dem on.co.ukwrote in message
news:C+******** ******@merlyn.d emon.co.uk...
>snip<
( Alternatively, consider
D = new Date(St.split('/').reverse().jo in('/'))
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.ne t.auwrote in message
news:11******** **************@ i42g2000cwa.goo glegroups.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.co m>, dated
Thu, 3 Aug 2006 11:06:49 remote, seen in news:comp.lang. javascript, Jim
Davis <ne********@vbo ston.composted :
>Part of this is are "dateFormat ()" and "timeFormat ()" methods. You can use
them to output the format you want like so:

myJSDate.forma tDate("yyyy-mm-dd") + " " + myJSDate.timeFo rmat("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.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 4 '06 #10

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

Similar topics

1
464
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 convert this field to a format I specify? Thanks. Li
2
1927
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 it fail in my production server. I don't know the reason?? My development machine: winXP Pro, VS.NET 2003 My Production machine: Win2000 server with SP4, .NET Framework 1.1 -- Best Regards,
2
4784
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
61211
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 convert DATETIME field into a more user friendly format directly in query? I can do the following in MySQL. How should it be done in Access? SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
4
2841
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 possible to do the same using javascript alone. that is , without using any additional softwar waiting for early reply
2
2684
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 t2_date>=convert(datetime,' " & text2.text &"'),cn,,,adcmdtext but there is a syntex error to converting datetime format into character string plz help me
4
4517
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 possible to convert the arrangement using 'Format' method? If so, please educate me how I can do such operation. Thank you!
3
30795
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
2166
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
8428
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
8339
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
8851
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...
1
8535
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4176
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
4338
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
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.