converting date format using javascript - php

I have a simple textfield with the type defied to be as date which attached with a jquery datepicker(). Now i have set the dateFormat() to be dd-mm-yy. All this works fine. But as i know MySql requires date in yyyy-mm-dd. So i was just wondering if i can convert that date format either using php or javascript to enter into the database.
E.g var date = $('#order_date').val(); gives value 26-2-2012. I need to convert this into 2012-02-26.
Note: There is also a 0 being added to the month.

Use PHP:
$date = $_POST['date']; // e.g. 06-08-2011
$mysql_date = date('Y-m-d', strtotime($date));
or
$date = explode('-', $_POST['date']);
$mysql_date = $date[2].'-'.$date[1].'-'.$date[1];
use $mysql_date to insert into the database.

You can do in javascript by parsing the input and loading it into a Date() object, and then using the getMonth, getDate, and getFullYear functions, as follows:
//Assume input is dd-mm-yyyy
var dateParts = $('#order_date').val().split("-");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
//format using getMonth(), getDate() and getFullYear() methods)
var formattedMonth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var formattedDate = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var output = date.getFullYear() + '-' + formattedMonth + '-' + formattedDate;
You can see more at this excellent StackOverflow post

did u try date.format("yyyy-mm-dd"); ?
u can also use "isoDate" in place of "yyyy-mm-dd"
and if u are using mysql u can use DATE_FORMAT(date,'%Y-%m-%d')

Related

how to change date format in jquery date coming from a datatable

aData[8] is the column number which shows date in dd-mm-yyyy format.
I want to change it to yyyy-mm-dd format for validation purpose.
var dueDate = new Date(aData[8]);
console.log(aData[8]);
var dt_to = $.datepicker.formatDate('dd-mm-yy', new Date(dueDate));
var dueDatetimestamp = dt_to.getTime();
I like to use moment.js to manipulate dates.
You could do something like that with it:
moment("13-08-2014", "DD-mm-YYYY").format("YYYY-mm-DD")
Consider this:
var str = '13-02-2014';//your format dd-mm-yyyy
var newar = str.split('-');
var tempDate = newar[2] + '-' + newar[1] + '-' + newar[0];
var d = new Date(tempDate);
console.log(d);//date object
console.log(tempDate);//new format yyyy-mm-dd
DEMO
you can use date.js to achieve :
var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[0] + '-' + dateAr[1] + '-' + dateAr[2];
DEMO
Personnally, I'm using jQuery.format.date(value,'date-format'). But this is a jQuery's plugin available at https://github.com/phstc/jquery-dateFormat
Very simple to use (example from Github) :
<script>
document.write($.format.date("2009-12-18 10:54:50.546", "Test: dd/MM/yyyy"));
document.write($.format.date("Wed Jan 13 10:43:41 CET 2010", "dd~MM~yyyy"));
</script>

Date to sql db fails

I have the below datepciker:
<script>
$(function() {
$( "#datepicker" ).datepicker({
dateFormat: 'mm-dd-YYYY'
}).val(getTodaysDate(0)); // For current date
});
function getTodaysDate (val) {
var t = new Date, day, month, year = t.getFullYear();
if (t.getDate() < 10) {
day = "0" + t.getDate();
}
else {
day = t.getDate();
}
if ((t.getMonth() + 1) < 10) {
month = "0" + (t.getMonth() + 1 - val);
}
else {
month = t.getMonth() + 1 - val;
}
return (day + '/' + month + '/' + year);
}
</script>
The input:
<input type="text" id="datepicker" name="datepicker">
And here I'm trying to insert the date to my MySQL db. There is no error message, the insert command runs OK, but the date field in my db is empty/NULL.
$date = $_POST['datepicker'];
$sql="INSERT INTO table (dt) VALUES ('$date')";
Is this some value type issue or what? The dt column in my db is DATE.
*UPDATE #Dwza:
So I modified the script:
dateFormat: 'YYYY-mm-dd'
and
return (year + '-' + month + '-' + day);
And the INSERT suggested by the link you mentioned:
$parts = explode('-', $_POST['datepicker']);
$date = "$parts[2]-$parts[0]-$parts[1]";
$sql="INSERT INTO transfer (dt) VALUES ('$date')";
Still no go.
**SOLVED:
$date = "$parts[0]-$parts[1]-$parts[2]";
in case that you try to insert a string (date) into a column from type DATE, you need a valid date format string.
this 11/07/2014 seems to be a german date format :D
check this answere
Quote:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.
this should solve your problem :)
change this
return (day + '/' + month + '/' + year);
to this
return (month + '/' + day + '/' + year);
or
return (year + '-' + month + '-' + day);
EDIT for Q:
You don't have to explode the data, its already valid date format after you change the retrun like i sayed above.
you could leave it like you have on beginning and than use explode.
You have to specify a name datepicker in your input field like so:
<input type="text" id="datepicker" name="datepicker">

store javascript UTC date in mysql . php

I have a json object which provides me the date in some kind of UTC format .
"date":new Date(Date.UTC(2013,1,5,13,53,47))
How can store this in mysql and what kind of column type should I use ? I'm using PHP to retrieve / store the data
Store this in the format of YYYY-mm-dd. You can't quite do this in a single line, so try this:
var d = new Date(Date.UTC(/* your stuff */));
...
"date": d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate()
EDIT:
On the PHP side say that date is in $_POST['date']. Use date('Y-m-d', strtotime($_POST['date'])) to get the value to store in MySQL.

How to convert a datetime string to UTC?

How can i convert a datetime string like this: 2012-09-03 22:00 US Estern to UTC timezone?
You should look at the DateTime object and its related functions in the documentation.
If your input date is already in a string format, DateTime::createFromFormat() will help you create an epoch-type integer date the object can work with. After that, it's just getTimezone() and setTimezone().
You could convert your timestamps from DB to epoch time with strtotime and wrap them in a special CSS class :
<span class="timestamp"><?php echo strtotime('2012-09-03 22:00'); ?></span>
And then with a bit of a Javascript (jQuery example), dynamically transform the unix epoch into a locale datetime :
$('.timestamp').each(function(){
var seconds = $(this).html();
var d = new Date(1000 * parseInt(seconds));
var t = (d.getMonth()<9 ? '0':'') + parseInt(d.getMonth()+1) + '/';
t+= (d.getDate()<10 ? '0' : '') + parseInt(d.getDate()) + '/';
t+= parseInt((d.getYear()<1000 ? d.getYear()+1900 : d.getYear())) + ' ';
t+= (d.getHours()<10 ? '0' : '') + d.getHours() + ':' + (d.getMinutes()<10 ? '0' : '') + d.getMinutes();
$(this).html(t);
});
This will output dates in the format mm/dd/yyyy hh:ii, relative to browser timezone.

Convert facebook time zone into my local time zone as facebook does

I am using facebook apis and getting created_time as
2012-06-06T16:20:43+0000
I have posted this status at about
21:57 (IST)
and i am getting 2012-06-06T16:20:43+0000
any help will be appreciated, to get the same time as i have posted to get the exact updates.
you can convert any timezone using this code:
$timestamp = strtotime("2012-06-06T16:20:43+0000"); //here you put your string with the tie
$dtime = new DateTime();
$dtime->setTimestamp($timestamp);
$localtz = new DateTimeZone("Asia/Calcutta"); //choose the correct PHP timezone
$dtime->setTimeZone($localtz); //we apply the timezone
$stringtime = $dtime->format('Y-m-d\TH:i:sO'); //here you return the time in the same format as facebook
$unixtime = $dtime->format('U'); //here u get the unix timestamp format of the same string
print $stringtime;
I've written a function earlier for this task,
I've updated it for your needs,
var fbDateFix = function(date){
var local = new Date(date.replace(/-/g,'/').replace('T',' ').replace('+0000',''));
local.setSeconds(local.getSeconds() + 19800);
return local;
}
var padZero = function(t){
if(t<10){
return '0' + t;
}
return t;
}
var d = fbDateFix('2012-06-06T16:20:43+0000');
console.log(d);
var month = padZero(+d.getMonth()+1);
var date = padZero(+d.getDate());
var hour = padZero(+d.getHours());
var min = padZero (+d.getMinutes());
var sec = padZero (+d.getSeconds());
console.log(d.getFullYear() + '-' + month + '-' + date + 'T' + hour + ':' + min + ':' + sec + '+0000')
Edit:
This works for me in php,
date_default_timezone_set('Asia/Calcutta');
$timestamp = strtotime('2012-06-06T16:20:43+0000');
$local_datetime = date('c',$timestamp);
echo $local_datetime;
It looks like the date returned to you is a UTC datetime. You need to convert it to your local timezone (IST)...
See the following SO question for converting datetimes using php:
php convert datetime to UTC
You can use PHP's strtotime to convert created_time to a UNIX timestamp. Then you can add or subtract your time zone offset (IST is UTC+05:30).

Categories