I need to get the value of Datetimepicker in my JavaScript function. I have made something like this, but it doesn't work:
$("#date").click( function(){
alert(document.getElementById('datetimepicker1').value);
});
It gives me 'undefined'
Either use:
$("#datetimepicker1").data("datetimepicker").getDate();
Or (from looking at the page source):
$("#datetimepicker1").find("input").val();
The returned value will be a Date (for the first example above), so you need to format it yourself:
var date = $("#datetimepicker1").data("datetimepicker").getDate(),
formatted = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours + ":" + date.getMinutes() + ":" + date.getSeconds();
alert(formatted);
Also, you could just set the format as an attribute:
<div id="datetimepicker1" class="date">
<input data-format="yyyy-MM-dd hh:mm:ss" type="text"></input>
</div>
and you could use the $("#datetimepicker1").find("input").val();
It seems the doc evolved.
One should now use :
$("#datetimepicker1").data("DateTimePicker").date().
NB : Doing so return a Moment object, not a Date object
To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:
$('#datetimepicker').data("DateTimePicker").FUNCTION()
So you can try the function:
$('#datetimepicker').data("DateTimePicker").date();
Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/
Or try:
$("#datetimepicker").data().date;
Since the return value has changed, $("#datetimepicker1").data("DateTimePicker").date() actually returns a moment object as Alexandre Bourlier stated:
It seems the doc evolved.
One should now use : $("#datetimepicker1").data("DateTimePicker").date().
NB : Doing so return a Moment object, not a Date object
Therefore, we must use .toDate() to change this statement to a date as such:
$("#datetimepicker1").data("DateTimePicker").date().toDate();
I'm using the latest Bootstrap 3 DateTime Picker (http://eonasdan.github.io/bootstrap-datetimepicker/)
This is how you should use DateTime Picker inline:
var selectedDate = $("#datetimepicker").find(".active").data("day");
The above returned: 03/23/2017
This is working for me using this Bootsrap Datetimepiker, it returns the value as it is shown in the datepicker input, e.g. 2019-04-11
$('#myDateTimePicker').on('click,focusout', function (){
var myDate = $("#myDateTimePicker").val();
//console.log(myDate);
//alert(myDate);
});
I tried all the above methods and I did not get the value properly in the same format, then I found this.
$("#datetimepicker1").find("input")[1].value;
The above code will return the value in the same format as in the datetime picker.
This may help you guys in the future.
Hope this was helpful..
Related
I'm receiving dates from my database in the format 2018-08-08 15:38:48 however I want it to show 3:38 pm instead.
I'm just unsure when to make this change, can I change it while it is being posted? They are dates of messages being sent to a person.
Current code:
<div v-for="messages in userMessages">
<div class="date">
{{ user.created_at }}
</div>
</div>
Output:
2018-08-08 15:38:48
How do I transform the date in vue? (when it is in a v-for?)
Vue does not offer date formatting. You will need your own filter to format the date. Or you use a package like the following: https://github.com/brockpetrie/vue-moment#readme
<span>{{ someDate | moment("hh:mm a") }}</span>
Vue.js does not natively allow dates to be formatted in a different way.
I suggest you to use more famous libraries like moment.js to format your dates however you want.
For example:
import moment from 'moment'
Vue.filter('formatDate', function(value) {
if (value) {
return moment(String(value)).format('MM/DD/YYYY hh:mm')
}
}
https://momentjs.com/
How do you use it?
You can use like this.
moment('2018-08-08 15:38:48').format('LTS'); // 03:38:48 PM
Your datetime format is not the ISO standard we would like, but we'll live with it... When handling dates, it's a good practice to convert them to date objects as soon as you receive them. If they're arriving in JSON, you can do this with a reviver function as the second argument to JSON.parse(). Here is a reviver function that will do the job for you...
Then,at the point you need to display, you can format your time with toLocaleTimeString()
function nReviver(key, value) {
var a;
if (typeof value === "string") {
a = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d*)?$/.exec(value);
if (a) {
return new Date(a[0]);
}
}
return value;
}
// do this when you receive your data from the server and all
// dates, wherever they are in the JSON, will be converted to date objects
var myObj = JSON.parse('{"myDate":"2018-08-08 15:38:48"}',nReviver)
// ...then, when you want to display, format with toLocaleTimeString()
console.log(
myObj.myDate.toLocaleTimeString({},{
hour12:true,
hour:'numeric',
minute:'numeric'
})
.toLowerCase()
)
I have a javascript date that I am passing via ajax to a php script then using the date in an sql insert into mysql database. I can't figure out how to format the date so the SQL call accepts it. Can anyone help with this?
In the AJAX call I've tried passing the date object as is, converting to JSON, to UTC.
The error I get is:
Incorrect date value: 'Thu, 01 May 1902 03:01:00 GMT' for column 'uspr_dob'
This all works if I remove the date line from the SQL code. ie I update the other fields but not the date. So everything else is working except the date passing.
jQuery date formation:
var dob = new Date(year, month, day, hours, minutes, 0, 0);
jQuery AJAX call:
var save_result = jQuery.ajax({
url: lb_path + "update_user.php",
data: { 'lb_user_id' : this.id,
'lb_dob' : this.dob.toUTCString(), //toJSON
... },
type: 'POST',
datatype: 'json',
success: function(data, status) {
...
}, // End success
error: function (xhr, ajaxOptions, thrownError) {
...
}
}); // End load the supplement list
PHP code is:
$sql = "UPDATE userpref
SET uspr_person_group = \"".$lb_gender."\",
uspr_diet_type = (SELECT diet_id FROM diet WHERE diet_name = \"".$lb_diet."\"),
uspr_exercise_profile = (SELECT exprof_id FROM exercise_profile WHERE exprof_name = \"".$lb_exercise."\"),
uspr_dob = \"".$lb_dob."\"
WHERE uspr_user_id = ".$lb_user_id;
If you use YYYY-MM-dd format you will never run into any issues. It is better to convert it before passing it to the server in your case.
Please refer to Get String in YYYYMMDD format from JS date object? .
OK - I found the problem - The database documentation showed the field in the table was DATETIME ... when actually it was DATE.
Once I spotted that and massaged the datetime string into MySQL's format it all worked beautifully!
Still I would think that there is an easier way to do this ... ie a date format in javascript that can be passed straight through AJAX, PHP then SQL and work without any formatting.
I want to add the result value plus already exists value in that textbox. but addition is not working concatenation is working
$.post('includes/ajax_timesheet.php', {
'action': 'add_kitamount',
'jobnumber': jobno,
'invoiceno': inv_no
}, function (data) {
var tot1 = $('#tot_dayrate').val();
var tot2 = $.trim(data);
var tot = tot1 + tot2;
alert(tot);
$("#tot_dayrate").val(tot);
});
Concatenation is happening because the values are being treated as string by + operator . Parse the values to number using any of the availaible javascript functions and then you will get correct total.
Ofcourse you need to handle for invalid inputs . Below is only showing an example for parse to number function.
var tot = parseInt(tot1) + parseInt(tot2);
Check here for string to number conversion and good explanation of difference between Number() and parseInt() , parseFloat() functions.
var tot = parseFloat(tot1) + parseFloat(tot2);
Convert to number
var tot = Number(tot1) + Number(tot2);
Or
var tot = parseInt(tot1) + tot2;
.val() returns the value of the element in String. You will first need to convert to to Number for performing arithmetic operations.
You can use Number() to convert the string into numbered format.
So your code would look something like this,
var tot1 = $('#tot_dayrate').val();
if(tot1!='') {
tot1=Number(tot1);
}
var tot2 = $.trim(data);
if(tot2!='') {
tot2=Number(tot2);
}
var tot = tot1 + tot2;
Make sure to check for blank value before converting String into int.
I have a database named user_job_apply(id, job_id, postby_id, applier_id, flag, flag_wall, time_apply).
The "time_apply" type in my database was set to :datetime
My problem is that the following piece of code inserts everything suceesfully in my databe, but it does not insert the value for $timeString. When I look in my database it shows 0000-00-00 00:00:00. Any idea what is the problem here?
I have tested by echoing $timeString and it displays date and time with success, but i cannot pass it into my database. Any idea how to fix this?
<?php
// the next two values comes from a form
$the_job_code = mysql_real_escape_string($_POST['jobid']);
$the_postedby = mysql_real_escape_string($_POST['postedby']);
// use it to get current time from user's computer
$timeString= '
<script language="javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd="0"+dd
}
if(mm<10) {
mm="0"+mm
}
today = mm+"/"+dd+"/"+yyyy + " " +today.getHours() + ":" + today.getMinutes()+":" + today.getSeconds();
document.write(today);
</script> ';
mysql_query("INSERT INTO `user_job_apply` VALUES ('', '$the_job_code', '$the_postedby ', '$session_user_id', '1', '1', '$timeString') ");
?>
Maybe you need use MySQL date format, like 'YYYY-MM-DD'?
It can be because of your Mysql localization settings and the dateformat, try what stepozer said 'YYYY-MM-DD'
today = yyyy+"/" +mm+"/"+dd+ " " +today.getHours() + ":" + today.getMinutes()+":" + today.getSeconds();
or you can just insert the current date and time directly on your sql using the function NOW()
mysql_query("INSERT INTO `user_job_apply` VALUES ('', '$the_job_code', '$the_postedby ', '$session_user_id', '1', '1', NOW()) ");
The "today" variable defined at the bottom of your Javascript block is not defined in a format compatible with MySQL.
It should be defined like this:
today = yyyy+"-"+mm+"/"+dd+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds();
Like this it will output in the format needed by MySQL to save in a "datetime" field.
EDIT:
The above solution only solves part of your problem.
The main problem here is that this code runs on the server-side after the form is submitted.
You should move the javascript block to the html file where the form resides (after the form) and write the "today" variable to a hidden form input called "timeString".
After submission you should receive this variable through the post:
$timeString = mysql_real_escape_string($_POST['timeString']);
EDIT 2:
First you need to create a hidden form input inside your form:
<input type="hidden" name="timeString" id="timeStringInput">
You need to copy the following block to your html file, right after the end of the form ():
<script language="javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd="0"+dd
}
if(mm<10) {
mm="0"+mm
}
today = yyyy+"/"+mm+"/"+dd+" "+today.getHours()+":"+today.getMinutes()+":"+ today.getSeconds();
document.getElementById('timeStringInput').value = today;
</script>
On the PHP file, replace the $timeString assignment (complete block) with:
$timeString = mysql_real_escape_string($_POST['timeString']);
I am trying to get the server date and time using an Ajax call. I am able to retrieve the value I need, but when I try to use it to create a javascript date object, I get an invalid date error. I tried to use trim to remove any spaces too. Any ideas?
Ajax call:
// ajax call to getcurrent server time
$.ajax({
type: GET',
url: 'datetime.php',
success: function(data) {
console.log("Data: " + data);
currentdate = new Date($.trim(data));
console.log("Current date from server: " + currentdate);
},
});
PHP Code:
<?php
echo date('y,m,d,H,i,s');
?>
Console Output (Chrome):
Data: 12,06,08,15,07,57
Current date from server: Invalid Date
You are trying to use a string as if it were literal code. Kind of like using eval, but without actually including the eval.
Yes, eval is one way to do it: currentdate = eval("return new Date("+$.trim(data)+");");
However eval is evil. Instead, you should do:
var elems = $.trim(data).explode(",");
elems[1]--; // remember months are zero-based in JS
currentdate = new Date(elems[0],elems[1],elems[2],elems[3],elems[4],elems[5]);
Even better, though, would be to have your PHP script be echo time();, then your JS could be:
currentdate = new Date();
currentdate.setTime(data);