I got 3 numeric text fields which are days, hours and min. I have scripted in such a way that user can only type 2 digit for each field.
Can someone help me to combine this 3 fields into one integer (which is a UNIX time) so that I can save it in the database as a single column time.
HTML
<table><tr>
<td><input id='days' type='text' maxLength='2' placeholder='Days'></td>
<td><input id='hours' type='text' maxLength='2' placeholder='hours'></td>
<td><input id='min' type='text' maxLength='2' placeholder='Min'></td>
</tr></table>
JavaScript
var day = document.getElementById('days').value;
var hours = document.getElementById('hours').value;
var min = document.getElementById('min').value;
How do I combine this 3 variable (day,hours,min) into one single unix time variable and save it in the database. ( I know how to save it in the database but ? How do I combine the 3 variable and save it in a single JavaScript variable ? )
For this, I'm using you want to use the current month and year? You need to post the fields to your PHP script and use strtotime to formulate a timestamp:
$timestamp = strtotime(date('Y-M') . '-' . $_POST['days'] . ' ' . $_POST['hours'] . ':' . $_POST['min']);
Or, using JavaScript:
var d = new Date();
var ts = Math.round((new Date(d.getFullYear(), d.getMonth(), $('#day').val(), $('#hours').val(), $('#min').val())).getTime() / 1000);
Unix timestamps are the number of seconds since the beginning of the unix epoch.
The javascript Date object has a getTime method that returns the number of milliseconds since the beginning of the unix epoch.
So, if you want the value calculated on the client side:
var time = new Date(0,0,day,hours,min);
var milliseconds = time.getTime();
var seconds = milliseconds / 1000;
I'm not including an example of how to send a value to the server and save it to the database - that completely depends on the server-side technology you are using, and a quick google or stackoverflow search will help you with that part.
Related
I want to pass the time variable extracted from the database as a Date function in jQuery and want to extract hours and minutes from it and want to store it in a javascript variable.
var time="<?php echo $row['time']; ?>";
var time=new Date(time);
var hrs=time.getHours();
var min=time.getMinutes();
Please find if there is any error in this code.
Without more knowledge I can't really give you an answer.
But its likely that you're expecting a Date Object, when in reality your DB is returning something else.
(Maybe a string?, a number?)
Make sure what type of data is exactly storen in your "time" variable. Would be my suggestion because I dont see errors in the code. Must be the logic
Really hope this helped but more insight into what your DB is doing would help getting a clear answer :)
Good Luck !
You could find answers for this all over Stackoverflow or read the docs on the date object.
However, here is an answer you might like
var myMinutes = 1; // This represent 1 minute subtraction
var myHours = 60; // This represent 60 minutes subtraction which is 1 hour
var dateMSubObject= new Date(oldDateObject.getTime() - myMinutes*60000); //Substracting your minutes variable
var dateHSubObject= new Date(oldDateObject.getTime() - myHours*60000); //Substracting your hours variable
To make it more managable you could do hours like this aswell for etc 24 hours
var myHours = 60*24; // This represent 24 hours subtraction
You could also make the above code a function which wil take paramters like units, type and from that return your desired result
The 60000 part is milliseconds and represents 1 minute.
And welcome to StackOverflow, if you take some time exploring the website you will quickly be able to find the most common questions usually followed by great answers :)
This did it for me:
let jsdate = new Date(unixtimestamp+1000);
example in use:
let a = new Date();
console.log("a ="+a)
let stamp = a.getTime()
console.log("stamp ="+stamp) // timestamp
let newTimeObj = new Date(stamp*1000)
console.log("newTimeObj :::::::"+newTimeObj)
OUTPUT::::
You need to convert the UNIX Timestamp(in seconds) which is coming from your PHP code to milliseconds, and then pass it as a parameter to a Date object.
Consider the below example in JavaScript:
//UNIX Timestamp from your PHP code
let timeInUNIXTimeStamp = "1581653281";
// Create a new JavaScript Date object based on the timestamp
// Multiplied by 1000 to convert it into milliseconds, from seconds, as Date object works in milliseconds
var date = new Date(timeInUNIXTimeStamp * 1000);
// Get Hours part from the timestamp
var hours = date.getHours();
// Get Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in H:M format
var timeInHMSFormat = hours + ':' + minutes.substr(-2);
console.log(timeInHMSFormat);
You can same achieve in PHP also, there you need to convert UNIX Timestamp to H:M format, using the date() function, where the first parameter will the format you wanted and the second will be your UNIX Timestamp.
Example: date("h:i", 1581653281);
Where h is hours, in 12-hours format
i is minutes
Read move about PHP's data() function Date function in php
Consider PHP the code below, inside your JavaScript:
var time="<?php echo date('h:i', $row['time']); ?>";
//Now Split the above string into array
var timeArray = time.split(":");
var hours = timeArray[0];
var minutes = timeArray[1];
For more detail see this answer Convert UNIX Timestamp
I don't finde anywhere how to add time to time, like adding 45 minutes to 45 minutes and having 1:30 (1 hour, 30 minutes).
I just find how to add time to actual Date.
Heres an example in PHP of what I'm looking for:
$seconds_toadd = 45;// VALUE TO GET FROM A TEXTBOX
$actual_value = '00:45'; //45 minutes, 0 hours is the actual value
$resultado = new DateTime($lectura_xml);
$resultado->add(new DateInterval('PT' . $seconds_toadd . 'S'));//This is how I add seconds in PHP
$stamp = $resultado->format('I:s');//Formatting result
echo $stamp;
Thank you.
Moment.js is a great library for date/time handling in JavaScript and better than the standard API and any homemade solution in many aspects.
Very simple but similar use case from their docs:
var a = moment.duration(1, 'd');
var b = moment.duration(2, 'd');
a.add(b).days(); // 3
Hello today I encountered an issue with time stamp conversions.. In my web form I'm using an bootstrap-datepicker where users can pick date and time. Afterwards I convert those values with moment.js to unix timestamp and pass it to PHP page. In the PHP page if the user is in different country the value is different and in the end in database is inserted wrong value.
So it's like the server timezone is Latvia/Riga GMT+2 and user from Georgia/Tbilisi has GTM+4. He's selecting start date 12.01.2017 15:00, Moment.js passes it to PHP page in the DB value of start date is inserted 12.01.2017 13:00.
Here is code from js
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
var start = moment.utc(start_date + ' ' + start_time, "DD.MM.YYYY HH:mm").tz("Europe/Riga");
afterwards var is passed via ajax to PHP script like start.unix()
In PHP it receives
$startDate = date('Y-m-d H:i:s', $_GET['start']);
And time is received by 2 hours earlier..
What can I do so the user selects time from anywhere on the world PHP inserts in DB as it selected correctly without timezone conversion.
You should never pass dates with timezones from client-to-server, always have the server be the boss in this case, otherwise you're inevitably going to have inconsistency issues in your database.
You either:
Always use UTC+0 dates.
Use keywords that represent a date (ie. yesterday, now, two days ago).
Using a keyword allows you to make the server decide which date do you want based on UTC+0 timezone.
TL;DR;
Always use UTC+0 datetimes and convert them server/client-side (it's your preference) depending on which timezone a user is on.
You can use following JS to get Client Timezone in JS:
var time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
In PHP:
function getDateTime($start_date, $start_time, $time_zone) {
$dateTime = $start_date . ' ' . $start_time;
$date = new DateTime($dateTime, new DateTimeZone($time_zone));
$serverTimeZone = date_default_timezone_get();
$date->setTimezone(new DateTimeZone($serverTimeZone));
return $date->format('Y-m-d H:i:sP');
}
This might help you to sync timezone
I am developing a website that allow user to see their equipments and know how much days passed till the repair started.
But i am having trouble getting the DATABASE information about the date.
I registered a column DATE and i made it TIMESTAMP with CURRENT_TIMESTAMP so it can automaticly atribut the date that joined the system.
I am using a script to get today's date and i put it in a table so it can show the user:
<script>
var days = new Date();
document.getElementById("days").innerHTML = days.toISOString().substr(0, 10);
</script>
Then i called a function that gets all equipment info ( client name, DATE, Type, etc...):
include_once('DataAccess.php');
$da = new DataAccess();
$res = $da->getEquipmentInfo();
while($row = mysqli_fetch_object($res)){
echo " <td id='days'></td> "; }
How do i make to calculate the difference between the database columns DATE and today's date to know how much days passed?
Thank you.
Convert both dates into unix and then find the difference between them and depending on if you want days, weeks, minutes, ect. you will have to convert. I dont have enough information for on your code and all your javascript to do it for you but here is a php example.
<?php
$now = time();
$db_unix = strtotime($res->theMysqlTimestamp);
$datediff = $now - $db_unix;
echo floor($datediff/(60*60*24));
?>
This takes the date now, your timestamp from mysql gets the unix timestamps, subtracts them, and then calculates the days difference between them.
I am creating a Javascript based date filter to filter files, which has date_created metadata.
I wish to create that date filter as a range slider with max/min (are static) and current selection. For this going to use jQuery UI slider component. Visible output has to be always in a format dd/mm/yyyy and I will show it for min/max and from/to range selectors.
While developing, I came to a question, which format I have to use on a hidden part to make steps inside the slider. Each step has to be 1 day. I decided to try with unix on hidden side. So I can easily convert unix into dd/mm/yyyy with my Javascript function:
function unixToDate(timestamp){
var date = new Date(timestamp * 1000);
var d = date.getDate(),
m = date.getMonth() + 1,
y = date.getFullYear();
return d + "/" + m + "/" + y;
}
And this function works well for me, however if step == 1day, I need 1 day value in unix to make addition (+) and subtraction (-) when user moves slider.
So which is that value of 1 day in unix, which I can add or subtract to when changing range?
Or any other alternatives to make date filter as slider…
One day is equal to currentTimeInUnixTime+(60*60*24)
That is because Unix time is simply the seconds since the beginning of epoch. 60 seconds make one minute. 60 minutes make an hour. And 24 hours make a day. Multiply them all, and add them to the current Unix time you have to get the Unix time for the next day.