Formatting date and time - JavaScript

Hi experts this follows on from an earlier question:
http://www.experts-exchange.com/questions/28697687/Combining-Date-and-Time-in-JavaScript.html
I am starting with a date formatted dd/mm/yyyy and trying to reformat the string to yyyy-mm-dd as follows:

 
var startdate = document.getElementById('<%=TxtStartDate.ClientID%>').value;
 var startparts = startdate.split('/');
 var mystartdate = new Date(startparts[2] + "-" + startparts[1] + "-" + startparts[0]);

Open in new window

then displaying the result to check:

if (startdate != '') {
                document.getElementById('<%=Txttest1.ClientID%>').value = mystartdate;
                
            }

Open in new window


The result I get for 23/07/2015 however is:

Thu Jul 23 01:00:00 UTC+0100 2015

Can anyone advise please?
forstersAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
>> var mystartdate = new Date(startparts[2] + "-" + startparts[1] + "-" + startparts[0]);
Change that to:
var mystartdate = startparts[2] + "-" + startparts[1] + "-" + startparts[0];

Open in new window


just concatenate the date parts.
0
Julian HansenCommented:
You can try something like this - however your sample date is incorrect. If you are going to use that format for date it should be mm/dd/yyyy. Consider 04/04/2015 - it is ambiguous as to what is the month and what is the day. Convention is if you use forward slashes it is US format of m/d/y and if you use - (hyphens) it is UTC (y-m-d).

This code formats the date as you want it - you can modify it as needed.

Date.prototype.ymd= function()
{
    return this.getFullYear().toString() +
        "-" +
        (("00" + (this.getMonth() +1)).substr(-2)) + "-" +
        (("00" + this.getDate()).substr(-2));
};

var testdate = new Date("03/27/2015");
alert(testdate.ymd());

Open in new window


Sample here
0
forstersAuthor Commented:
Ahhh - thanks that worked (so easy when you know how) - I'm wondering if I just made a new problem for myself though...

you'll see from the code below that I am trying to reformat two datetimes to calc the duration in hh:mm between the two; I get a 'difference' result of NaN - presumably because these are now just strings - is there a solution?

var startdate = document.getElementById('<%=TxtStartDate.ClientID%>').value;
            var enddate = document.getElementById('<%=TxtEndDate.ClientID%>').value;
            
            var starthours = document.getElementById('<%=DDLStartHrs.ClientID%>').value;
            var startmins = document.getElementById('<%=DDLStartMins.ClientID%>').value;
            
            var endhours = document.getElementById('<%=DDLStopHrs.ClientID%>').value;
            var endmins = document.getElementById('<%=DDLStopMins.ClientID%>').value;
           

            var startparts = startdate.split('/');
            var endparts = enddate.split('/');
            

            var mystartdate = startparts[2] + "-" + startparts[1] + "-" + startparts[0];
            var myenddate = endparts[2] + "-" + endparts[1] + "-" + endparts[0];
            //var myenddate = new Date(endparts[2] + "-" + endparts[1] + "-" + endparts[0]);
            //var UTCstart = mystartdate.toUTCString();
            //var UTCend = myenddate.toUTCString();
            var started = (mystartdate + 'T' + starthours + ':' + startmins + ':00.000Z')
            var ended = (myenddate + 'T' + endhours + ':' + endmins + ':00.000Z');
            var difference = (ended - started) / (1000 * 3600);
            
            if (startdate != '') {
                document.getElementById('<%=Txttest1.ClientID%>').value = started;
                
            }

            if (enddate != '') {
                document.getElementById('<%=Txttest2.ClientID%>').value = ended;
            }

            if (startdate != '' && enddate != '') {
                document.getElementById('<%=Txttest3.ClientID%>').value = difference;
            }

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

forstersAuthor Commented:
hi Julian,

I take your point re. date format but dd/mm/yyyy is the format generated by the calendar control.
Struggling to follow your example - sorry maybe my reply to hielo will clarify where I'm at..
0
Julian HansenCommented:
Here is a documented version.
// EXTEND THE DATE OBJECT BY ADDING A NEW FUNCTION
// CALLED ymd
Date.prototype.ymd= function()
{
    // RETURN A STRING MADE UP OF 
    // THE FULL YEAR CONCATENATED TO ...

    return this.getFullYear().toString() +

    // THE SEPARATOR, CONCATENATED TO ...
        "-" +
    // THE MONTH. A SIMPLE TRICK TO GET 0 PADDED STRING
    // CONCATENATE THE MONTH (WHICH IS ZERO BASED
    // SO WE HAVE TO ADD 1) AND THEN TAKE THE RIGHT 2
    // CHAR'S  CONCATENATED TO ...
        (("00" + (this.getMonth() +1)).substr(-2)) + 

    // THE SEPARATOR, CONCATENATED TO ...
        "-" +

    // THE DAY. getDate RETURNS THE DAY (1-31)AND WE USE THE SAME 
    // TRICK FOR PADDING WITH ZERO'S
        (("00" + this.getDate()).substr(-2));
};

// CREATE A NEW DATE
var testdate = new Date("03/27/2015");

// OUTPUT IT IN yyyy-mm-dd FORMAT WITH THE NEW FUNCTION
alert(testdate.ymd());

Open in new window

0
hieloCommented:
>> var difference = (ended - started) / (1000 * 3600);
What "difference" type are you looking for? Just hours?  what if it exceeds 24?
0
forstersAuthor Commented:
thanks both- I am looking for a 'difference' of hh:mm - it will not exceed 24hrs in this scenario.
0
hieloCommented:
var started = (mystartdate + 'T' + starthours + ':' + startmins + ':00.000Z')
var ended = (myenddate + 'T' + endhours + ':' + endmins + ':00.000Z');
var difference = daysBetween( new Date(Date.parse(started)), new Date(Date.parse(ended)) );

alert(difference);


/* slightly modified version of
    http://www.htmlgoodies.com/html5/javascript/calculating-the-difference-between-two-dates-in-javascript.html#fbid=tjy3peN9kEH
*/
function daysBetween ( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
  //take out milliseconds
  difference_ms = difference_ms/1000;
  var seconds = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60;
  var minutes = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60;
  var hours = Math.floor(difference_ms % 24);
  var days = Math.floor(difference_ms/24);

  //return (hours < 10 ? '0'+hours:hours) + ':' + (minutes<10 ? '0'+minutes:minutes) + ':' + (seconds<10?'0'+seconds:seconds);
  return (hours < 10 ? '0'+hours:hours) + ':' + (minutes<10 ? '0'+minutes:minutes) ;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
forstersAuthor Commented:
fab thanks so much - that's working
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.