Input [type = date] format value dynamically generated in php

I have an input with a value dynamically generated

<input name="etd" type"date" value="<?php echo $row[0]; ?>"> 

To support html5 date input, this value is assigned the yyyy-mm-dd date format, and the mm/dd/yyyy format is displayed correctly in html5 browsers.

The problem occurs in browsers without html5, where the assigned value is displayed as text directly ( yyyy-mm-dd format). My attempt to convert this value to mm/dd/yyyy format using jQuery is as follows:

 <script> $('input[type="date"]').each({ var now = new Date($(this).attr('value')); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); $(this).val(today); }); </script> 

but it doesn’t work, I am new to jQuery, so I think something is with it.

UPDATE:

I use this code to host date pickers in browsers that do not support html5, this does not solve my problem with dates retrieved from the database, but the if clause can somehow distinguish between html5 browsers. I think maybe I can use this condition to filter jQuery code (this code I'm looking for)

 <script> $(function() { if (!Modernizr.inputtypes['date']) { $('input[type=date]').datepicker({ dateFormat: 'mm/dd/yy' }); } }); </script> 
+4
source share
2 answers

Try it; Here is the Fiddle link .

Html:

 <input name="etd" type="date" value="1919-03-12"> 

Js:

 $( document ).ready(function() { $('input[type=date]').each(function (this){ var datestring = $(this).val(); var dateobj = new Date(datestring); var formattedstring = dateobj.getUTCDate()+"/"+dateobj.getUTCMonth()+"/"+dateobj.getUTCFullYear(); $(this).val(formattedstring); }); }); 

Also note that when you set the date and month , for individual values, it must be preceded by zero. For example, month 7 should be 07.

Btw, your code is missing the = icon in the line like " please fix this :)

+1
source

In JavaScript, you can actually use split in a string. Much easier than passing it through a Date object.

 $('input[type="date"]').each(function(){ var now = $(this).attr('value').split("-"); var today = now[1]+"/"+now[2]+"/"+now[0]; //mm/dd/yyyy $(this).val(today); }); 

split will crack the string into arrays using a delimiter. Trait in this case. The following array is created:

 ['yyyy', 'mm', 'dd']; 

Now you can rearrange these parts of the array to the desired line.

Demonstration:

 $('input[type="date"]').each(function(){ var now = $(this).attr('value').split("-"); var today = now[1]+"/"+now[2]+"/"+now[0]; //mm/dd/yyyy $(this).val(today); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="date" value="2015-08-09" /> 
0
source

All Articles