Working on an app whereby am capturing some input fields using bootstrap datepicker. Am displaying the format in dd/mm/yy format to the user which works fine. On the backend (build in Laravel PHP), I need to convert it to yy-mm-dd format which is the required format when storing the date field in the API.
In the controller when I dump the data I get 28/01/2019 but when I convert it I get 1970-01-01. What could be the issue?
Markup
<div class="form-line registar love {{ $errors->has('dob') ? ' has-error' : '' }}">
<input type="text" placeholder="Date of Birth *" class="form-input dateTextBox" name="dob" id="dob" value="{{isset($user->dob) ? $user->dob : old('dob') }}" required>
</div>
Javascript Logic (Bootstrap datpicker)
var maxBirthdayDate = new Date();
maxBirthdayDate.setFullYear( maxBirthdayDate.getFullYear() - 18 );
maxBirthdayDate.setMonth(11,31);
$( function() {
$( "#dob" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy',
maxDate: maxBirthdayDate,
yearRange: '1900:'+maxBirthdayDate.getFullYear(),
});
});
Controller Logic
public function validateDate(Request $request){
//dd($request->dob);
//28/02/2019 after dd() above
//Convert
$dobCv = date("Y-d-m", strtotime($request->dob));
dd($dobCv);
//1970-01-01 after dd() above
}
Why don't you use Laravel build in Carbon
$date = Carbon::createFromFormat('d/m/Y', $date);
Then you can do $date->toDateTimeString(); or whatever you want to do with the Carbon date object
You can simply use Carbon :
$dobCv = Carbon::createFromFormat('d/m/Y', $request->dob)->format('Y-m-d');
And don't forget the import :
use Carbon\Carbon;
Encode it in json format and send it to the controller
Changing input type text into date might help you.
eg: <input type="date" .......>
You have the problem because forward slash (/) signifies American M/D/Y formatting in strtotime and in your example 28/02/2019 28 is month. So strtotime returns false. I recommend you to use Carbon library as was said above or change / with - if you want your way:
$dobCv = date("Y-d-m", strtotime(str_replace('/', '-', $request->dob)));
Version :"khill/lavacharts": "3.1.*",
Controller provides carbon date object and datatable is completed as per below ;
In PHP code
$dataTable = \Lava::DataTable();
$formatter = \Lava::DateFormat([
'pattern' => 'MMM d, HH:mm',
//'timeZone' => '', //same results without timezone parameter or with 'timeZone' => 2,
]);
$DataTable->addDateColumn('closing hour', $formatter)
->addNumberColumn('closing price')
->addNumberColumn('product evaluation')
->setDateTimeFormat('Y-m-d H:i:s')
->setTimezone('UTC') ; //added but no effect
for (...){
//$hour_start-->toIso8601String() == 2018-09-07T17:00:00+00:00 6430.4420188271
$dataTable->addRow([$hour_start->toDateTimeString(), $hourly_closing_price ,$hourly_value]);
}
**return $dataTable->toJson();//added after answer of WhiteHat**
Log::info(' dataTable '.$dataTable->toJson());
However while logged php json of datatable is as per below, for each row :
{"c":[{"v":"Date(2018,8,7,17,0,0)"},{"v":6430.442018827109}...
In javascript after ajax call to my Laravel controller, received json is a per below
{"c":[{"v":"2018-09-07T15:00:00.000Z","f":"Sep 7, 17:00"},{"v":6430.442018827109},{"v":0}]} .
There a 2 hour difference between f column (my UTC date) and v column (my UTC date minus 2h).
I changed my browser local time zone for test but no effect.
Data provided are in UTC, server is in UTC and timezone set on chart is UTC but somewhere in google chart, a 2h difference is applied.
It seems google server doesnt consider the dates sent as UTC time and change the v value while keeping the f formatted value
With
$formatter = \Lava::DateFormat([
'pattern' => 'MMM d, HH:mm',
'timeZone' => 0,
]);
=> f and v column on same timezone but changed as if input date was not UTC (but UTC+2)
{"c":[{"v":"2018-09-07T15:00:00.000Z","f":"Sep 7,
15:00"},{"v":6430.442018827109},{"v":0}]}
Any clue someone?
i'm not familiar with Lavacharts,
but I would question the format of the data when it actually reaches the browser.
whether, it is actually in json format.
not sure what addRow does here, but it appears to be loading a simple array,
not a json object.
addRow([$hour_start->toDateTimeString(), $hourly_closing_price ,$hourly_value]);
in javascript, when you create a date from a string,
in most cases, it will be adjusted for the timezone.
see this answer for more info there. --> Why does Date.parse give incorrect results?
however, google's json date string representation will result in the exact date,
with no adjustment for timezone.
take a look at the following example,
in the first row, google's json date string is used.
in the second, we use the new Date() constructor from a formatted string.
you'll notice the browser does not change the timezone of the first row,
but does on the second.
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = new google.visualization.DataTable({
cols: [
{type: 'datetime'}
],
rows: [
{c:[{v: 'Date(2018,8,7,17,0,0)'}]},
{c:[{v: new Date('2018-09-07T17:00:00+00:00')}]}
]
});
var formatDate = new google.visualization.DateFormat({
pattern: 'MM/dd/yyyy HH:mm:ss'
});
formatDate.format(data, 0);
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(data);
document.getElementById('test-date0').innerHTML = data.getValue(0, 0);
document.getElementById('test-date1').innerHTML = data.getValue(1, 0);
});
div {
margin-bottom: 6px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Google table chart</div>
<div id="table"></div>
<div>raw data</div>
<div id="test-date0"></div>
<div id="test-date1"></div>
EDIT
one option might be to use a data view to adjust the date by the timezone offset on the browser,
this should put the date back to the original value sent from the server...
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = new google.visualization.DataTable({
cols: [
{type: 'datetime'}
],
rows: [
{c:[{v: 'Date(2018,8,7,17,0,0)'}]},
{c:[{v: new Date('2018-09-07T17:00:00+00:00')}]}
]
});
var formatDate = new google.visualization.DateFormat({
pattern: 'MM/dd/yyyy HH:mm:ss'
});
// create data view
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
// one minute in milliseconds
var oneMinute = (60 * 1000);
// get date from data table
var rowDate = dt.getValue(row, 0);
// Adjust date for timezone
rowDate = new Date(rowDate.getTime() + (oneMinute * rowDate.getTimezoneOffset()));
// return new value and formatted value
return {
v: rowDate,
f: formatDate.formatValue(rowDate)
};
},
type: data.getColumnType(0)
}]);
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(view);
document.getElementById('test-date0').innerHTML = view.getValue(0, 0);
document.getElementById('test-date1').innerHTML = view.getValue(1, 0);
});
div {
margin-bottom: 6px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Google table chart</div>
<div id="table"></div>
<div>raw data</div>
<div id="test-date0"></div>
<div id="test-date1"></div>
As explained by WhiteHat, this is an issue on how my browser & googleChart interpret as local dates the json containing google dataTable with utc dates.
1)
What is done by my browser with a date as : new Date(2018,8,7,6,0,0) :
console.log('time2 '+ new Date(2018,8,7,6,0,0)) ->Fri Sep 07 2018 06:00:00 GMT+0200 (Romance Daylight Time)
What i want :
console.log('time1'+ new Date(Date.UTC(2018,8,7,6,0,0))) ->Fri Sep 07 2018 08:00:00 GMT+0200 (Romance Daylight Time)
see point 2 for solution.
2) I need to retrieve my json utc date on indeed this format : new Date(2018,8,7,6,0,0)
Javascript call to google chart changes received server utc dates (ex: {"v":"Date(2018,8,7,17,0,0)"}) in json in a local date formatted as [{"v":"2018-09-07T15:00:00.000Z","f":"Sep 7, 17:00"} so i need to intercept the string date before it gets changed
var dataTable
$.getJSON('/chart', function (dataJson) {
// dataTable dataJson on format : "v":"Date(2018,7,31,19,0,0)"
dataTable = dataJson
dataToLoad = $.extend(true,{},dataJson); //clone it as the object dataToLoad will be modified by google chart when loaded per lava
lava.loadData('chart', dataToLoad , function (data) {
console.log('data'+JSON.stringify(dataToLoad )) //dataTable dates are put on format : "v":"2018-08-31T16:00:00.000Z","f":"Aug 31, 18:00"
});
})
use dataTable...
//To get the right timezone on my dates, i did something like:
string_timestamp ; string_timestamp = datatable.data['rows'][item.row]['c'][0]['v'] //this is my received UTC date formatted as "Date(2018,8,7,17,0,0)" in dataTable
temp=(string_timestamp.replace("Date(","")).replace(")","")
str1= temp.split(',');
date2=new Date(Date.UTC(str1[0],str1[1],str1[2],str1[3],str1[4],str1[5]))
I'm trying a simple thing as displaying a date column in a kendo ui grid in Angular using the following:
<kendo-grid-column field="date" title="Date" type="date" format="{0:d}"></kendo-grid-column>
However the result is:
'2017-04-30T09:00:00'
I guess you are using the data received from your backend. It that case your should convert your date field to Date type manually.
return this.http.get("url")
.map((res: Response) => {
let result = res.json();
result.forEach((x) => {
x.dateField= new Date(x.dateField);
});
return result;
})
Use the following in place of your format code: format="{0:dd/MM/yyyy}". You have to specify which format you wish to use
I'd like to be able to manually enter a date into the dateTime picker and have it persist to the control.
Example Code: http://jsfiddle.net/awDA4/39/
<script src="http://cdn.kendostatic.com/2013.1.514/js/kendo.all.min.js"></script>
<div>
<input id="datepicker" style="width:200px" />
</div>
$(document).ready(function() {
$("#datepicker").kendoDateTimePicker();
});
Say you enter a date by hand into the control like '08/08/2013'
If you then post the form the start of time (01/01/0001) date is sent
If you pick a time from the time drop down it reverts to the current date
Any ideas what I might be doing wrong?
I thought about marking the input as readonly/disabled but surely you should be able to allow users to type a date by hand.
I needed to include additional parseFormats when initializing the DateTimePicker
$(document).ready(function() {
$("#datepicker").kendoDateTimePicker({
parseFormats: ["MMMM yyyy", "HH:mm", "MM/dd/yyyy"] //format also will be added to parseFormats
});
MM/dd/yyyy was added and I can now manually key in dates with that format
I am trying to integrate the jquery datepicker to an input field which i am creating dynamically using script..
my script is like...
function getDate(id)
{
$('.pop-up-link').show();
$.ajax({
url : 'gettartDate.jav',
data : 'Id='+id,
success : function(dateStr)
{
var htmlStr = 'Start Date : <input type="text" class="datepicker" id="startDateId" value="'+dateStr.StartDate+'"/>';
$(".pop-info").html(htmlString);
$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true});
}
}
I am calling this script when i need to edit the date in database and to add new entry to database. When i need to add new entry, im setting id as 0 and returning a blank string..
Now my problem. the datepicker works perfectly for edit functionality.. But when i add a new entry, the datepicker ui comes.. But the date is not updating to that input field. Again, when i put an alert to display selected date,i noticed that only date is changing.. The year and month is not changing, even when i change it
It could be down to the fact you are dynamically adding the datepicker with the same ID's, i was having the same issue with dynamically created datepickers. if there was anyway you could take out the Id attr and use the Name attr it should work.
so you should have the following
var htmlStr = 'Start Date : <input type="text" class="datepicker" name="startDateId" value="'+dateStr.StartDate+'"/>';
Try using the refresh method on .datepicker like so:
$( ".datepicker" ).datepicker( "refresh" );