Getting proper unix timestamp with JS for facebook scheduler - javascript

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.

Related

How to get time in no space format ? javascript

I want to save data to database in order of their upload, I decided to use current time in ISO, like if date is -> 29 June 2021 Tuesday, 19(hour):36(minute):45(seconds), I extracted time from it as 193645 this ensured to display data according to time for that day,
but if the seconds is single digit for example(14(hour):32(minute):05(seconds)) but then it displays 14325 without 0.
And if possible I want the time for this date - (29 June 2021 Tuesday, 19(hour):36(minute):45(seconds))
to (without those brackets) - 21(for year)06(for month)29(for day)19(for hour)36(for minute)45(for seconds)
let _today = new Date().toISOString()
let dateToday = new Date(_today)
_time = dateToday.getHours().toString() + dateToday.getMinutes().toString() + dateToday.getSeconds().toString()
console.log(_time)
This is my current code
You can remove the separator symbols and take the substring you need.
Like in this function
symbolless = (date) => date.toISOString().replace(/[\-\.\:ZT]/g,"").substr(2,10)
Handling timezones is a little more difficult as JavaScript uses UTC-0 as the timezone for .toISOString().
Get the timezone in negative minutes using .getTimezoneOffset() and multiply with -60000 to get the correct offset in milliseconds. Be aware the timezone will depend on the machines local timezone, so deployments or users in other timezones will yield different results when running the command (this might be fixed in the future with the introduction of temporal).
symbolless = (date) => new Date(date.getTime() + date.getTimezoneOffset() * -60000)
.toISOString()
.replace(/[\-\.\:ZT]/g,"")
.substr(2,10)
Running the new function symbolless(new Date('August 19, 1975 23:15:30 UTC')) will yield 7508200015 in my timezone. In the following format:
YYMMDDHHMM
7508200015
This is correct as the date is now in UTC+1.

How to format MySQL timestamp using jquery

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"))

Incorrect time shown in Google LineChart

There are dates stored as timestamp in the MySQL database. If I view them with phpMyAdmin the correct time is shown. In a php script I try to output the date with UNIX_TIMESTAMP into a Javascript Date Object (new Date()). When displaying the data in a Google Chart there is a time offset of +2:00 hours (my current timezone). I also looked into the timestamp and a timestamp converter told me that the local time is correct and UTC time is -2:00 hours.
In the php-script I already set the timezone with date_default_timezone_set(). SELECT ##global.time_zone, ##session.time_zone; outputs SYSTEM. But I still get the time offset. Now I use
SELECT UNIX_TIMESTAMP(CONVERT_TZ(Timestamp, "+02:00", ##session.time_zone)) ...
and I get the correct data. Does this mean that the data is stored with a 2 hours offset? Why does phpMyAdmin showing me the correct date and time? Or does the Google chart expects UTC time and the browser automatically adds the difference for the timezone?
What is the real problem here?
Now I wrote a function which converts the timestamp from the database into an UTC date:
function getDateinUTC(timestamp){
var date = new Date(timestamp * 1000);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we'll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
return new Date(year, month, day, hours, minutes, seconds);
}
When I create the DataTable I simply call the function as shown here:
rows: [
{c:[{v:getDateinUTC(stamp)}, {v: value}]},
]
You have to replace stamp and value with your php-code which fills the place.
This idea is based on the article Automatic timezone conversion in JavaScript by David Mytton.
So far the times seems to be correct.

getTimezoneOffset() method return different time on localhost and on server

I have a function in which I am calculating the current user location time based on the Australian NSW timezone minus the local offset. So for example I want to compare an event starting time in Australian (NSW) local time vs my local time I am getting the correct value if I open the website on my localhost. However I am getting 1 hour different if I visit the website on the uploaded server (test environment). So if the correct time is 04:00 on localhost I am getting 05:00 on the test environment.
Here is my function:
var date = {
formatFullDate: function(date, gmtTimeOffset) {
var localDate = this.getLocalTimeFromAustraliaTime(date, gmtTimeOffset),
month = this.addZeroToFront(localDate.getMonth() + 1),
hour = this.addZeroToFront(localDate.getHours()),
minute = this.addZeroToFront(localDate.getMinutes());
return localDate.getDate() + '/' + month + '/' + localDate.getFullYear() + ' ' + hour + ':' + minute;
},
formatTime: function(date, gmtTimeOffset) {
var localDate = this.getLocalTimeFromAustraliaTime(date, gmtTimeOffset),
hour = this.addZeroToFront(localDate.getHours()),
minute = this.addZeroToFront(localDate.getMinutes());
return hour + ':' + minute;
},
addZeroToFront: function(whatever) {
if (whatever < 10) whatever = "0" + whatever;
return whatever;
},
getUTCtimeOffset: function() {
var date = new Date();
return date.getTimezoneOffset();
},
getLocalTimeFromAustraliaTime: function (date, gmtTimeOffset) {
var gmtTime = new Date(date.getTime() - gmtTimeOffset*1000),
localOffset = new Date().getTimezoneOffset(),
localDate = new Date(gmtTime - localOffset*60*1000);
return localDate;
}
}
Some general details for my specific case:
Aus/NSQ time zone: UTC/GMT +10 hours
Finnish timezone: UTC/GMT +3 hours
So there is 7 hours different between AUS/NSW and Finland and the result is correctly displayed on localhost but not on the test environment. I am not sure why there is 1 hour different between these 2 cases.
EDIT: 1
This is how I am displaying the current local time
var tr = $('<tr style="cursor:pointer; color: #000000" id="' + categoryId + '_' + raceNumber + '_nextRaceTr"/>')
.append($('<td/>')
.append($('<p/>')
.html(date.formatTime(new Date(value.time), value.timezoneOffset))))
Where as time and timezoneOffset are the JSON response.
P.S - Dont pay attention if I am missing enclosing brackets or any other syntax error. I have only copied a small piece of code just to show how I am displaying the time on HTML.
The JavaScript Date object is always influenced by the time zone settings of the environment where it is running. In most cases, that's the user's browser. Users of different time zones will get different results running your code.
In general, you should beware of any code that follows a pattern like this:
var adjustedDate = new Date(someOtherDate.getTime() - someOffset);
You might think you're cleverly adjusting the behavior of the Date object to a different time zone, but in reality you're changing the referenced point in time and leaving the time zone the same!
Also, consider where you have:
var localOffset = new Date().getTimezoneOffset();
You might think you're getting the time zone offset for the user, but actually you are just getting the current time zone offset for the user. Remember, new Date() initializes to the current moment in time. The moment you're working with might have a completely different offset, depending on if the user happens to be in a time zone with daylight saving time or not and whether it was in effect at that time.
As far as your code goes, it's a bit difficult to tell what you're after since you didn't give examples of your input. You might want to take a look at moment.js, which has most of the formatting functions you might be looking for.
BTW - I don't see anything in your code that would actually bind it to any of the Australian time zones.
I recommend that you convert all times to UTC and store in that format. When you display a time for a user, you can convert to their local time from UTC. Just make sure that you do all calculations/conversions on the same machine on which you are going to display the time (e.g. if you are displaying dates in a webpage, don't calculate the local time on the server, send down an epoch timestamp to the browser and then convert it to local time using JavaScript).
var d = new Date(1413409549000);
alert(d.toString());

How to make a form active to users in certian weeks on certian days during certian time period javascript

I am working on a web form for IE.
I have my form completed, but I need the users to be able to only use the form in even weeks on Sundays after 6pm until 3pm on Monday (next day). This needs to be in EST no matter where the user is.
I haven't worked alot with Javascript and am at a complete loss on how to do this. What I am having the most trouble with is the determining today is in an even week for the year. (even weeks are pay weeks and this is only when the form should be used.)
I would like the today's date is in an even week criteria to be the first filter. I have written if, if else statements to determine if today's day and hours meet my criteria demands .getUTCDay() and .getUTCHours().
I was thinking of using an array of the qualifying Sunday and Monday dates but wasn't sure how to write the if statement for looking to see if today's date is in the array. Any help would be most appreciated.
You can use the JavaScript Date object (See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date) to see the current date, you can even parse it to whatever format you like. Then do your form logic.
For more elaborate Date manipulations, you can check out Moment.js http://momentjs.com/ it's a very comprehensive library for dealing with date/time.
Your first issue is to get a date object in the correct time. The timezone "EST" is used in at least 3 different parts of the world for different time zones, but I'll assume you want the US EST of UTC-05:00.
Javascript date objects have a UTC timevalue at their heart, so you can get a local date object, subtract 5 hrs, then use the UTC methods to get values for the equivalent US EST timezone. Once you have that date object, you just need to get the week number per the answer here except that you should use UTC methods instead of plain date methods (e.g. getUTCFullYear rather than getFullYear).
Note that this will ignore daylight saving time at the client location and that EST does not indicate whether daylight saving is in force or not. It's usually given a different time zone designator (e.g. places that use US EST and also daylight saving call their timezone EDT, which will be UTC-04:00).
Here is some code that should do the job, note that it's only lightly tested. I decided to include the local timezone offset to make it consistent and probably easier to understand.
// Returns true or false if current date is
// an even week of the year in timezone UTC-5:00
// Adjust local date object to be UTC-5:00 object
// Provide a date object to test, or undefined for
// current date
function isPayWeek(d) {
d = d? new Date(d) : new Date();
// Adjust for local timezone and US EST in minutes
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - 300);
// return true if week number is even (note: zero is even)
return !(getWeekNumber(d)[1] % 2)
}
function getWeekNumber(d) {
d = new Date(d);
d.setHours(0,0,0);
d.setDate(d.getDate() + 4 - (d.getDay()||7));
var yearStart = new Date(d.getFullYear(),0,1);
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7)
// Return array of year and week number
return [d.getFullYear(), weekNo];
}
var d = new Date(2013,0,20,20,0,0); // 2013-01-20T10:00:00Z
var w = getWeekNumber(d); // week 3, 2013
alert(d + '\n' + 'week: ' + w + '\n' + isPayWeek(d)); // false
var d = new Date(2012,11,31,20,0,0); // 2012-12-31T10:00:00Z
var w = getWeekNumber(d); // week 1, 2013
alert(d + '\n' + 'week: ' + w + '\n' + isPayWeek(d)); // false
var d = new Date(2013,0,7,20,0,0); // 2013-01-07T10:00:00Z
var w = getWeekNumber(d); // week 2, 2013
alert(d + '\n' + 'week: ' + w + '\n' + isPayWeek(d)); // true

Categories