Unix time from API to normal format - javascript

I'm using openweathermap for my application https://openweathermap.org/current and I need to input the current time with weather in the city.
The time in the API in UNIX format. How I can input the time in application in normal format (h:m:s)
Line with date/time from API (dt....Time of data calculation, unix, UTC)
Below my JS code
document.querySelector('#city').addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>");
}
};
});
function show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Pressure</strong>: " + data.main.pressure + "hPa</h3>" +
"<h3><strong>Humidity</strong>: " + data.main.humidity + " %</h3>" +
"<h3><strong>Min. Temperature</strong>: " + data.main.temp_min + "°C</h3>" +
"<h3><strong>Max. Temperature</strong>: " + data.main.temp_max + "°C</h3>" +
"<h3><strong>Wind Speed</strong>: " + data.wind.speed + "m/s</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}

If you mean letting the user input some date+time in local format and getting UNIX timestamp for it, you can use Date.parse(), just it returns the milliseconds while you need seconds, so divide the result with 1000. (The base date+time is the same for both, 1970 Jan 1. 00:00:00 UTC)
function doConvert(event){
unix.textContent=Math.round(Date.parse(event.target.value)/1000);
}
<input type="datetime-local" onchange="doConvert(event)"><br>
<div id="unix"></div>
If you mean the other way around (UNIX time to readable), use Date() (remember to convert seconds to milliseconds) and its toLocaleString():
function doConvert(event){
time.textContent=new Date(event.target.valueAsNumber*1000).toLocaleString();
}
<input type="number" oninput="doConvert(event)"><br>
<div id="time"></div>

UnixTime = https://en.wikipedia.org/wiki/Unix_time
var UnixTime = 1525478400;
var myDate = new Date(UnixTime*1000);
var HH = myDate.getHours();
var MM = myDate.getMinutes();
var SS = myDate.getSeconds();
document.write(HH+":"+MM+":"+SS);

Related

GoogleSheets script to sendEmail upon form submission, how should I handle a formatting error for a blank cell?

Simple call logger/lead sheet generator using Google Forms and a script to send out the lead upon submission. I'm getting a format error when the user does not input a date into the field. I don't want to require an appt. time/date in the form. Here is my code:
function sendEmails() {
//gets list of
var leadss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LatestLeadSheet");
var leadList = leadss.getRange(3, 1, leadss.getLastRow() - 2, leadss.getLastColumn()).getValues();
var timeZone = Session.getScriptTimeZone();
var today = Utilities.formatDate(new Date(), timeZone, "MM/dd/yyyy"); //Today's date for email subject line
var fullMessage = ""; //clears fullMessage variable
// Creates body of email. Looping through each array from LatestLeadSheet tab
for (var j = 0; j < leadList.length; j++) {
var message = "Client Name: " + leadList[j][1] + "\n" +
"Client Phone: " + leadList[j][3] + "\n" +
"Client Email: " + leadList[j][8] + "\n" +
"Interested in: " + leadList[j][5] + "\n" +
"Quoted rate of: " + leadList[j][6] + "\n" +
"Notes: " + leadList[j][7] + "\n" +
"Appointment Set for: " + Utilities.formatDate(leadList[j][10], timeZone, "HH:mm MM/dd/yyyy") + "\n"
//+"At: "+Utilities.formatDate(leadList[j][11],timeZone,"h:mm a") + "\n\n"
+
"Referral Source: " + leadList[j][2] + "\n" +
"Other Info: " + leadList[j][4] + "\n" +
"Documents were sent (Y/N): " + leadList[j][9] + "\n" +
"Call was taken at: " + Utilities.formatDate(leadList[j][0], timeZone, "HH:mm MM/dd/yyyy") + "\n" +
"Call was logged by: " + leadList[j][12] + "\n\n\n\n";
var fullMessage = fullMessage + message;
}
//Sends email to each recipient listed on SalesTeam tab
var subject = "DMS Call Sheet from: " + today;
var emailss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SalesTeam");
var lr = emailss.getLastRow();
for (var i = 2; i <= lr; i++) {
var currentEmail = emailss.getRange(i, 2).getValue();
MailApp.sendEmail(currentEmail, subject, "Please follow up with the following potential clients: \n\n" + fullMessage)
}
}

JavaScript - Remove rows dynamically after 2mins

I am calling a webapi using get method which will give json data and I am display as a table from that data. the code which I have given below is working fine. I got around 25 rows(dynamically" of data when I fit the service. this webpage will be refreshed using signalR. when any changes in DB immediately it should reflect in the webpage.
My question is if "" + item.TakeupType + "" value is "Completed" or "cancelled" this row background should change to gray color and after 2mins row should be remove from the webpage.
Note:
1) Only 22 rows should display on webpage in orderby asc Datetime.
2) Completed/cancelled items from DB should will display on the webpage for 2 mins and drop off.
My code :
Hide Expand Copy Code
//Webapi call - To load info status.
function LoadinfoStatus() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('x-api-key', '9024024A-024-485C024-6BC2024DA');
}
});
$.ajax({
type: "GET",
url: "https://mywebsites.net/version1/info/494",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
//Function to get DateFormat
function getFormattedDate(date) {
// debugger;
var inputdate = new Date(date);
var currentdate = new Date();
var strTime = getFormattedTime(inputdate);
var rngStrTime = getFormattedTime(add_minutes(inputdate, 5));
if (inputdate > currentdate) {
return inputdate.getDate() + '/' + (inputdate.getMonth() == 0 ? 12 : inputdate.getMonth()) + " " + strTime + " - " + rngStrTime;
}
else {
return strTime + " - " + rngStrTime;
//return day + "/" + month + " - " + strTime;
}
}
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes * 60000);
}
function getFormattedTime(inputdate) {
var day = inputdate.getDate();
var month = inputdate.getMonth() + 1;
var hours = inputdate.getHours();
var minutes = inputdate.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ampm;
}
$.each(data, function (i, item) {
var rows = "<tr ' " + (item.Count > 100 ? "data-id='" + item.orderId + "'" : "") + (item.TakeupType == "Cancelled" ? "style='background-color: gray; color: white'" : "") + " align= 'center' > " +
"" + "" + "" + "" +
"" + item.user.firstName + " " + item.user.lastName.charAt(0) + "." + "" +
"" + item.TakeupType + "" +
"" + (item.Count == undefined ? "$" + " " + 0 : "$" + " " + item.Count) + "" +
"" + getFormattedDate(item.TakeupTimeUtc) + "" +
"= 100 ? "style='background-color: darkorange; color: white'>***" : ">") + "" +
"";
var $tbody = $('tblOrders tbody');
$('#tblOrders').append(rows);
}); //End of foreach Loop
registerEvents();
// console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
}

Ajax validation post error html

I am trying to code chat box with ajax, but when I make the call, the php file shatbox.php doesn't appear. Here is the code and the GitHubDiff.
GitHubb Diff
$(document).ready(function(){
$('#submit').on('click',function(){
var name = $('#name').val();
var shout = $('#shout').val();
var date = getDate();
var dataString = 'name=' + name + '&shout=' + shout + '&date' + date;
// validation
if(name == '' || shout == ''){
alert('please fill Your name and shout');
}else{
$.ajax({
type:"POST",
url:"../jschat/shoutbox.php",
data: dataString,
cache: false,
success: function(html){
$('#shout ul').prepend(html);
}
});
}
return false ;
});
});
function getDate(){
var date;
date = new date;
date = date.getUTCFullYear() +'-'+
('00' + (date.getUTCMonth() +1 )).slice(-2)+'-'+
('00' + date.getUTCDate().slice(-2)+' '+
('00' + date.getUTCHours().slice(-2)+ ':'+
('00' + date.getUTCMinutes().slice(-2)+':'+
('00' + date.getUTCSeconds().slice(-2);
return date;
}
There are 2 errors in the function getDate:
1.Date object is case-sensitive
2.There are some missing closing parentheses starting from date.getUTCMonth
function getDate() {
var date = new Date;
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
return date;
}
This may be the cause of your issue.
file location seems to be the issue
url:"../jschat/shoutbox.php",
try this
url:"../shoutbox.php",

JS: Formatting time and date display on website

I have a script that prints the current date and time in JavaScript, but when it prints time, it's missing one 0. Here is the code:
var currentdate = new Date();
var datetime = "0" + currentdate.getDate() + ".0"
+ (currentdate.getMonth()+1) + "."
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();
document.write(datetime);
It should print 04.03.2016 15:04 and prints 04.03.2016 15:4.
Two digit minutes print fine.
Any leads?
Try this
var formatDateDigit = function (i) {
return i <= 9 ? ("0" + i) : i;
};
var currentdate = new Date();
var datetime = formatDateDigit(currentdate.getDate()) + "."
+ formatDateDigit(currentdate.getMonth()+1) + "."
+ currentdate.getFullYear() + " "
+ formatDateDigit(currentdate.getHours()) + ":"
+ formatDateDigit(currentdate.getMinutes());
document.getElementById('my_output_here').innerHTML = datetime;
<div id="my_output_here"></div>

SQL node.js Syntax error on what seems to be a valid query?

I'm running an update on a table to set a position. I've extracted the query and manually run it on my database and works fine but when passed through connection.query() it seems to think there's a syntax error in my node.js console.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
var input = ', moving_datetime = ' + datetime;
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}
Here is the syntax error:
Here's the input data value of 'position' variable:
{ x: '-605', y: '-257', moving: 0 }
I hope I'm not being too much of a dunce and sorry for the low quality question.
Thanks
This function will generate SQL code which is missing quotes around the datetime variable, resulting in invalid SQL code.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
# Here!
var input = ', moving_datetime = \'' + datetime + '\''
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}

Categories