How to format MySQL timestamp using jquery - javascript

I read timestamp from MySQL db (is type timestamp).
Like this: 2017-04-01 15:34:31
I want to format this date using jquery and set up to some span element.
I am new in jquery and I don't know how to do it.
Thank you.

Try the DATE_FORMAT(date,format) function in MySQL. Something like:
DATE_FORMAT(NOW(),'%m-%d-%Y')
would give you 04-01-2017. Then wrap that in a <span>.
If you are using PHP then
strftime('%m-%d-%Y',$timestamp);
is an alternative. there are plenty of examples in Stack Overflow; Google will get you there.

If you would are receving the timestamp on the client side you can Convert a Unix timestamp to time in JavaScript
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
To add the formatted text to a span you could use javascript or jQuery
// Javascript
document.querySelector("span").text(formattedTime);
// jQuery
$("span").text(formattedTime);
For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.
Additionally:
If you must use jQuery instead of Javascript, consider a plugin
https://github.com/phstc/jquery-dateFormat
There is Javascript library https://momentjs.com/ for time
There is a great JS talk about time https://www.youtube.com/watch?v=2BdFg5JT9lg

Date(Date.parse(data.timestamp[i]))
This works assuming you are iterating through timestamps sent to the frontend from a Mysql query, which returns arrays. You could also write it like:
Date(Date.parse("2020-01-08 06:36:59"))

Related

Getting proper unix timestamp with JS for facebook scheduler

I'm trying to make scheduled posts to Facebook with the PHP SDK (normal posts are working fine, just issues with scheduling)
I use dropdowns for date and time choices which I retrieve and use Moments.js to get the Unix timestamp of:
var year = document.getElementById("selectYear").value;
var month = document.getElementById("selectMonth").value;
var day = document.getElementById("selectDay").value;
var time = document.getElementById("selectTime").value;
//in this example month is 1 day is 1 year is 2019 and time is 09:00:00
var timeStamp = ( moment(month + '-' + day + '-' + year + '-' + time).unix() )*1000
However, when I make the call I get the Facebook PHP SDK Error #100: The specified scheduled publish time is invalid
Is this not the proper unix timestamp?
A Unix time stamp counts the seconds since 1970. Javascript does the same, but in milliseconds.
You are multiplying the output of unix() by 1000, effectively creating a timestamp you can easily handle in JS, but it's not a Unix timestamp anymore. Just don't do that multiplication and you should be fine.

Incorrect time while copy pasting a date time value using google apps script [duplicate]

I'm trying to get from a time formatted Cell (hh:mm:ss) the hour value, the values can be bigger 24:00:00 for example 20000:00:00 should give 20000:
Table:
if your read the Value of E1:
var total = sheet.getRange("E1").getValue();
Logger.log(total);
The result is:
Sat Apr 12 07:09:21 GMT+00:09 1902
Now I've tried to convert it to a Date object and get the Unix time stamp of it:
var date = new Date(total);
var milsec = date.getTime();
Logger.log(Utilities.formatString("%11.6f",milsec));
var hours = milsec / 1000 / 60 / 60;
Logger.log(hours)
1374127872020.000000
381702.1866722222
The question is how to get the correct value of 20000 ?
Expanding on what Serge did, I wrote some functions that should be a bit easier to read and take into account timezone differences between the spreadsheet and the script.
function getValueAsSeconds(range) {
var value = range.getValue();
// Get the date value in the spreadsheet's timezone.
var spreadsheetTimezone = range.getSheet().getParent().getSpreadsheetTimeZone();
var dateString = Utilities.formatDate(value, spreadsheetTimezone,
'EEE, d MMM yyyy HH:mm:ss');
var date = new Date(dateString);
// Initialize the date of the epoch.
var epoch = new Date('Dec 30, 1899 00:00:00');
// Calculate the number of milliseconds between the epoch and the value.
var diff = date.getTime() - epoch.getTime();
// Convert the milliseconds to seconds and return.
return Math.round(diff / 1000);
}
function getValueAsMinutes(range) {
return getValueAsSeconds(range) / 60;
}
function getValueAsHours(range) {
return getValueAsMinutes(range) / 60;
}
You can use these functions like so:
var range = SpreadsheetApp.getActiveSheet().getRange('A1');
Logger.log(getValueAsHours(range));
Needless to say, this is a lot of work to get the number of hours from a range. Please star Issue 402 which is a feature request to have the ability to get the literal string value from a cell.
There are two new functions getDisplayValue() and getDisplayValues() that returns the datetime or anything exactly the way it looks to you on a Spreadsheet. Check out the documentation here
The value you see (Sat Apr 12 07:09:21 GMT+00:09 1902) is the equivalent date in Javascript standard time that is 20000 hours later than ref date.
you should simply remove the spreadsheet reference value from your result to get what you want.
This code does the trick :
function getHours(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = sh.getRange('E1').getValue();
var eqDate = new Date(cellValue);// this is the date object corresponding to your cell value in JS standard
Logger.log('Cell Date in JS format '+eqDate)
Logger.log('ref date in JS '+new Date(0,0,0,0,0,0));
var testOnZero = eqDate.getTime();Logger.log('Use this with a cell value = 0 to check the value to use in the next line of code '+testOnZero);
var hours = (eqDate.getTime()+ 2.2091616E12 )/3600000 ; // getTime retrieves the value in milliseconds, 2.2091616E12 is the difference between javascript ref and spreadsheet ref.
Logger.log('Value in hours with offset correction : '+hours); // show result in hours (obtained by dividing by 3600000)
}
note : this code gets only hours , if your going to have minutes and/or seconds then it should be developped to handle that too... let us know if you need it.
EDIT : a word of explanation...
Spreadsheets use a reference date of 12/30/1899 while Javascript is using 01/01/1970, that means there is a difference of 25568 days between both references. All this assuming we use the same time zone in both systems. When we convert a date value in a spreadsheet to a javascript date object the GAS engine automatically adds the difference to keep consistency between dates.
In this case we don't want to know the real date of something but rather an absolute hours value, ie a "duration", so we need to remove the 25568 day offset. This is done using the getTime() method that returns milliseconds counted from the JS reference date, the only thing we have to know is the value in milliseconds of the spreadsheet reference date and substract this value from the actual date object. Then a bit of maths to get hours instead of milliseconds and we're done.
I know this seems a bit complicated and I'm not sure my attempt to explain will really clarify the question but it's always worth trying isn't it ?
Anyway the result is what we needed as long as (as stated in the comments) one adjust the offset value according to the time zone settings of the spreadsheet. It would of course be possible to let the script handle that automatically but it would have make the script more complex, not sure it's really necessary.
For simple spreadsheets you may be able to change your spreadsheet timezone to GMT without daylight saving and use this short conversion function:
function durationToSeconds(value) {
var timezoneName = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (timezoneName != "Etc/GMT") {
throw new Error("Timezone must be GMT to handle time durations, found " + timezoneName);
}
return (Number(value) + 2209161600000) / 1000;
}
Eric Koleda's answer is in many ways more general. I wrote this while trying to understand how it handles the corner cases with the spreadsheet timezone, browser timezone and the timezone changes in 1900 in Alaska and Stockholm.
Make a cell somewhere with a duration value of "00:00:00". This cell will be used as a reference. Could be a hidden cell, or a cell in a different sheet with config values. E.g. as below:
then write a function with two parameters - 1) value you want to process, and 2) reference value of "00:00:00". E.g.:
function gethours(val, ref) {
let dv = new Date(val)
let dr = new Date(ref)
return (dv.getTime() - dr.getTime())/(1000*60*60)
}
Since whatever Sheets are doing with the Duration type is exactly the same for both, we can now convert them to Dates and subtract, which gives correct value. In the code example above I used .getTime() which gives number of milliseconds since Jan 1, 1970, ... .
If we tried to compute what is exactly happening to the value, and make corrections, code gets too complicated.
One caveat: if the number of hours is very large say 200,000:00:00 there is substantial fractional value showing up since days/years are not exactly 24hrs/365days (? speculating here). Specifically, 200000:00:00 gives 200,000.16 as a result.

Comparing a datetime from a get request with the current date time in JavaScript

I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565

Meteor - MongoDb - How to get seconds remaining between current data time and future date time

I want to get seconds remaining between a current dataTime and future dateTime.
I am using Meteor + MongoDb.
In Mongo DataTime is saved like this:
2015-12-11T06:14:39.671Z
I want seconds remaining between current datatime and future or expiry datetime.
keep your time data in epoch format which is basically storing data in milliseconds. then you'll be easy able to compare using momentJS or substracting. And in MongoDB , this data will be stored as Number type not Date
var time= (new Date).getTime();
this piece of code will return time in milliseconds.
The javascript Date can handle the sample input as listed in your question. If that format is consistant, the following should get you your answer:
var difference = (new Date(databaseDate).getTime()-Date.now())/1000;
Where Date.getTime() and Date.now() are in milliseconds (hence the 1000).

Add specified minutes to time using javascript

How we can add minutes to time, I want to add:
time = 21:36:13 and minutes 21:33
and want to get result 21:57:46
A JavaScript Date object stores time as the number of milliseconds since 1970/01/01 00:00:00 (in what should be UTC if the rest of your application is written properly). To add minutes and seconds, simply multiply te values to get the equivalent number of milliseconds, something like this: newDate = new Date(oldDate.getTime() + (((minutesToAdd * 60) + secondsToAdd) * 1000))
You should think about what you expect to happen during daylight saving time transitions. If the application is designed properly, the value in the Date object will be UTC, so the calculation above will always work correctly, but obviously the displayed value will be formatted as local time.
You may find a library such as Datejs useful.
What are you using to represent time? if you are using a native Date object, you can do something like this:
var addTime = function (baseDate, hours, minutes, seconds) {
return new Date(baseDate.getTime() + hours*3600000 + minutes*60000 + seconds*1000);
}
This is basically creating a new Date object adding a series of hours, minutes and seconds to the base Date provided (all of it in milliseconds). Here's the reference to work with Date objects.
You can use Date object with only taking interest in time. Here is your example:
function Foo()
{
time = new Date();
time.setHours(21);
time.setMinutes(36);
time.setSeconds(13);
time.setMinutes(time.getMinutes() + 21);
time.setSeconds(time.getSeconds() + 33);
alert(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
}
Hope it helps :D

Categories