0

Is there an easier way of getting a datetime from a string such as this: "29 March, 2014" in JAVASCRIPT

I've done it within PHP, but I want to fiddle with some front end to add days to the date etc..

Here is the required PHP code to achieve this:

function removeDateComma($string){
    $without_comma = preg_replace('/,/', '', $string);
    return $without_comma;
}

function getYearMonthDayFromDate($string){
    $array  = array();
    $string = removeDateComma($string);
    $string = strtotime($string);
    $year   = date('Y', $string);  
    $month  = date('m', strtotime("-1 month", $string));  
    $day    = date('d', $string);
    $array['year'] = $year;
    $array['month'] = $month;
    $array['day'] = $day; 
    return $array;
}

Calling this to get the required datetime:

$from = getYearMonthDayFromDate($_REQUEST['from_date']);

Can anyone come up with a solution to this problem? Getting the same result but in javascript?

Edit:

It's already implemented in PHP. I need to do it at the front end i.e. no form submission, I cant send anything anywhere, i've got to get this date from an input field, i.e. var field = document.getElementById("input_from").value; so that will be in the format 11 Month, 2014. So i've got this string sitting here which is useless, I need to get each individual value, i.e. the year: 2014, month: 03 or 3 and day: 11

Thanks!

2 Answers 2

1

Try this

 function getMonthName( monthNumber ) 
    {
        var monthNames = new Array("January", "February", "March", 
      "April", "May", "June", "July", "August", "September", 
      "October", "November", "December");
      return monthNames[monthNumber ]; 
    }
    var field = $("#input_from").val();

     var date1 = new Date(field); 
        var cMonth = date1.getMonth();
        var newdate = getMonthName(cMonth)   + " "+ date1.getDate() + ", " + date1.getFullYear();
alert(newdate);

Fiddle: http://jsfiddle.net/chetangawai/MNbjw/

Sign up to request clarification or add additional context in comments.

2 Comments

That looks more like it! I'll have a crack now :)
Yes this works perfectly, thank you for your time! reputation++ :D
0

easy solution

 $date = date('Y-m-d' , strtotime('"29 March, 2014"'));

or add 2 days to it

 $date = date('Y-m-d' , strtotime('+2 days' , strtotime('"29 March, 2014"')));

7 Comments

in javascript, so i'd have to get the field contents then run a function on the value
this is php, just send the value over and handle with php
how about using Date() function of javascript??
yes, thats what i'm using, but I cant seem to find a solution to this particular problem
what do you want to do exactly?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.