Related
I need to calculate the distance between coordinates.
I am using the Google Maps DistanceMatrix API:
getDistanceMatrix() async {
try {
var response = await Dio().get('https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${widget.miLatitud},${widget.miLongitud}&origins=${location.latitude},${location.longitude}&key=...');
print("distancia es ${response}");
} catch (e) {
print(e);
}
}
Which is the proper way to extract the distance from the response?
Here you have the response output:
distancia es {"destination_addresses":["Carrer de Sant Ramon, 62, 08140 Caldes de Montbui, Barcelona, Spain"],"origin_addresses":["Plaça de la Porxada, 32, 08401 Granollers, Barcelona, Spain"],"rows":[{"elements":[{"distance":{"text":"13.0 km","value":13012},"duration":{"text":"21 mins","value":1234},"status":"OK"}]}],"status":"OK"}
This is the beautified JSON file:
{
"destination_addresses":[
"Carrer de Sant Ramon, 62, 08140 Caldes de Montbui, Barcelona, Spain"
],
"origin_addresses":[
"Plaça de la Porxada, 32, 08401 Granollers, Barcelona, Spain"
],
"rows":[
{
"elements":[
{
"distance":{
"text":"13.0 km",
"value":13012
},
"duration":{
"text":"21 mins",
"value":1234
},
"status":"OK"
}
]
}
],
"status":"OK"
}
As you can see, you can get the distance if you go to rows-elements-distance-value, where you would get the result in meters.
var generateEvents = function () {
var eventData = [];
var eventSubjects = [
'Bering Sea Gold', 'Technology', 'Maintenance', 'Meeting', 'Travelling', 'Annual Conference', 'Birthday Celebration',
'Farewell Celebration', 'Wedding Anniversary', 'Alaska: The Last Frontier', 'Deadliest Catch', 'Sports Day', 'MoonShiners',
'Close Encounters', 'HighWay Thru Hell', 'Daily Planet', 'Cash Cab', 'Basketball Practice', 'Rugby Match', 'Guitar Class',
'Music Lessons', 'Doctor checkup', 'Brazil - Mexico', 'Opening ceremony', 'Final presentation'
];
var weekDate = new Date(new Date().setDate(new Date().getDate() - new Date().getDay()));
var startDate = new Date(weekDate.getFullYear(), weekDate.getMonth(), weekDate.getDate(), 10, 0);
var endDate = new Date(weekDate.getFullYear(), weekDate.getMonth(), weekDate.getDate(), 11, 30);
eventData.push({
Id: 1,
Subject: eventSubjects[Math.floor(Math.random() * (24 - 0 + 1) + 0)],
StartTime: startDate,
EndTime: endDate,
Location: '',
Description: 'Event Scheduled',
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;INTERVAL=1;COUNT=10;',
IsAllDay: false,
IsReadonly: false,
CalendarId: 1
});
I have tried inspecting the code and tried to add the input field eventData, but not working. I want to add the Input field of my choice and want to send the input field data to the firestore database.
I show date by this in ejs
<%= new Date();%>
it give me result
Tue Feb 02 2016 16:02:24 GMT+0530 (IST)
But I need to show as
19th January, 2016
How can I do this in ejs?
You can use moment
In your controller,
var moment = require('moment');
exports.index = function(req, res) {
res.render('index', { moment: moment });
}
In your html,
<html>
<h1><%= moment().format('Do MMMM, YYYY'); %></h1>
</html>
EDIT :
Using basic JS
const suffixMap = {
one: 'st',
two: 'nd',
few: 'rd',
other: 'th',
};
const date = new Date();
const dateDay = date.getDate();
const dateMonth = date.toLocaleString('default', {month: 'long'});
const dateYear = date.getFullYear();
const pluralRule = new Intl.PluralRules('en-GB', {type: 'ordinal'});
const dateOrdinal = suffixMap[pluralRule.select(dateDay)]
const ordinalDateString = `${dateDay}${dateOrdinal} ${dateMonth}, ${dateYear}`;
// Expected output: 25th August, 2020
(Adapted from this answer)
const date = new Date();
const dateDay = date.getDate();
const dateMonth = date.toLocaleString('default', {month: 'long'});
const dateYear = date.getFullYear();
// DETERMINE DATE ORDINAL
let dateOrdinal = 'th';
dateOrdinal = ([1, 21, 31].indexOf(dateDay) > -1) ? 'st' : dateOrdinal;
dateOrdinal = ([2, 22].indexOf(dateDay) > -1) ? 'nd' : dateOrdinal;
dateOrdinal = ([3, 23].indexOf(dateDay) > -1) ? 'rd' : dateOrdinal;
// FORMAT DATE AS STRING
const ordinalDateString = `${dateDay}${dateOrdinal} ${dateMonth}, ${dateYear}`;
// Expected output: 25th August, 2020
Or, if you can live without ordinal day (th, nd, rd etc) you could use basic JS
<%= new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'long', day: '2-digit'}).format(new Date()) %>
// Expected output: 25 August 2020
You don't need moment js, you can simply use this
<%= new Date().getFullYear();%>
Post is old but in case anyone runs into the issue.
You can eliminate installing moment and write one little line of code.
adding .toDateString() will provide you with the above format in ejs.
however, Moment is used for more detailed date, such as Day, or month or year etc...
For a better code management, you can add the code(below) in app.js/server.js. This will save moment in the res.locals.moment at the time of starting the app. By doing this you can access the moment variable from any ejs page.
app.js/server.js:
const express = require("express");
const app = express();
const moment = require("moment");
app.use((req, res, next)=>{
res.locals.moment = moment;
next();
});
something.ejs
<p><%= moment(yourDateVariable).format('Do MMMM, YYYY') %></p>
Here Do will result with 19th.You can check it here https://momentjs.com/docs/#/displaying/format/. Hope this will help.
You can do this:
<%= moment(user.date).format( 'MMM-DD-YYYY') %>
The problem with most of the answers on this page is that they will format the date using the server's locale, but you probably want them rendered in the user's locale. For example, if your server is in Virginia, your dates will be displayed in English in Eastern Time, but a user in another country will probably want them displayed differently.
The following code snippet will render date using the user's locale. There's room for improvement, but it's a starting point:
<p>
<script type="text/javascript">
document.write(
new Date("<%= date.toISOString() %>").toLocaleDateString()
);
</script>
</p>
This takes the date on the server, converts it to an ISO-8601 string, and interpolates it into a little JavaScript snippet that runs client-side to produce the correct localized output.
For more information on toLocaleString, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
// I have tested this in a for loop, it seems to be ok.
<% let d = new Date(); %>
<% let day = d.getDate(); %>
<% let m = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]; %>
<% let month = m[d.getMonth()]; %>
<% let year = d.getFullYear(); %>
<% let newdate = day + "th " + month + ", " + year; %>
<%= newdate %> // 22th July, 2022
// You can use the if...else statement for the ordinal number
How can I find the difference between two dates in DB2 (excluding weekends)?
Are there any functions that will do this in DB2? Or do I need to write a query myself?
There is AFAIK no such function. It is however easy to write a query that calculates this:
with cal(d) as (
values date('2015-01-01') -- start_date
union all
select d + 1 day from cal
where d < '2015-01-15' -- end_date
) select count(case when dayofweek(d) between 2 and 6 then 1 end)
from cal;
If you do a lot of these kind of calculations you might want to create a calendar table, you can add attributes like national holiday etc to this table.
you can use this function:
DAYOFWEEK(CURRENT_DATE)
The following calculation will return the number of working days between two dates:
[Week(End Date) - Week(Start Date)] * 5 + [DayofWeek(Start Date) - DayofWeek(End Date)]
This will only work if the functions for Week and Day or equivalent are native to the database driver. Client Access and Sybase native connection both support these functions.
The Week function will give the integer value of the week of the year selected. The DayofWeek will give an Integer value from 1-7 for the day selected.
IBM Support Working Days Between Two Dates
This is the best way to implement difference between two dates excluding weekend means Saturday and Sunday and also excluding national holiday....
/******
* First, we'll extend the date object with some functionality.
* We'll add an .each() function, as well as an .adjust() function.
* .each() will give us the ability to loop between two dates, whether
* by 'day', 'week' or 'month'.
* .adjust() will allow us to move a given day by a given unit. This is used
* like so: currentDate.adjust('days', 1) to increment by one day.
******/
Date.prototype.each = function(endDate, part, step, fn, bind){
var fromDate = new Date(this.getTime()),
toDate = new Date(endDate.getTime()),
pm = fromDate <= toDate? 1:-1,
i = 0;
while( (pm === 1 && fromDate <= toDate) || (pm === -1 && fromDate >= toDate) ){
if(fn.call(bind, fromDate, i, this) === false) break;
i += step;
fromDate.adjust(part, step*pm);
}
return this;
};
Date.prototype.adjust = function(part, amount){
part = part.toLowerCase();
var map = {
years: 'FullYear', months: 'Month', weeks: 'Hours', days: 'Hours', hours: 'Hours',
minutes: 'Minutes', seconds: 'Seconds', milliseconds: 'Milliseconds',
utcyears: 'UTCFullYear', utcmonths: 'UTCMonth', weeks: 'UTCHours', utcdays: 'UTCHours',
utchours: 'UTCHours', utcminutes: 'UTCMinutes', utcseconds: 'UTCSeconds', utcmilliseconds: 'UTCMilliseconds'
},
mapPart = map[part];
if(part == 'weeks' || part == 'utcweeks')
amount *= 168;
if(part == 'days' || part == 'utcdays')
amount *= 24;
this['set'+ mapPart]( this['get'+ mapPart]() + amount );
return this;
}
/*******
* An array of national holidays. This is used to test for the exclusion of given
* days. While this list is national days, you could tailor it to regional, state
* or given religious observances. Whatever.
******/
natDays = [
{
month: 1,
date: 26,
type: "national - us",
name: "New Year's Day"
},
{
month: 1,
date: 21,
type: "national - us",
name: "Martin Luther King Day"
},
{
month: 2,
date: 18,
type: "national - us",
name: "President's Day (Washington's Birthday"
},
{
month: 5,
date: 27,
type: "national - us",
name: "Memorial Day"
},
{
month: 7,
date: 4,
type: "national - us",
name: "Independence Day"
},
{
month: 9,
date: 2,
type: "national - us",
name: "Labor Day"
},
{
month: 10,
date: 14,
type: "national - us",
name: "Columbus Day"
},
{
month: 11,
date: 11,
type: "national - us",
name: "Veteran's Day"
},
{
month: 11,
date: 29,
type: "national - us",
name: "Thanksgiving Day"
},
{
month: 12,
date: 25,
type: "national - us",
name: "Christmas Day"
}
];
/******
* This uses the national holidays array we just set, and checks a given day to see
* if it's in the list. If so, it returns true and the name of the holiday, if not
* it returns false.
*****/
function nationalDay(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == (natDays[i].month-1)
&& date.getDate() == natDays[i].date) {
return [true, natDays[i].name];
}
}
return [false, null];
}
/******
* This function takes two dates, as start and end date, and iterates through the
* dates between them. For each date, it checks if the current date is a week day.
* If it is, it then checks if it isn't a holiday. In this case, it increments
* the business day counter.
******/
function calcBusinessDays(startDate, endDate) {
// input given as Date objects
var iDateDiff=0, holidays = [];
startDate.each(endDate, 'days', 1, function(currentDate, currentStep, thisDate){
if(currentDate.getDay() != 0 && currentDate.getDay() != 6 ) {
var isAHoliday = nationalDay(currentDate);
if(!isAHoliday[0]){
iDateDiff += 1;
} else {
holidays.push(isAHoliday[1]);
}
}
});
return {count: iDateDiff, holidays: holidays};
};
$(function(){
var results, exclusions;
$( "#startDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#endDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#endDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$("#calculateMe").on("click", function(){
var startDate = new Date($("#startDate").val()),
endDate = new Date($("#endDate").val() );
// Calculate the number of business days. This returns an object, with
// two members: count and holidays
results = calcBusinessDays(startDate, endDate);
exclusions = "Excluded weekends";
if (results.holidays.length > 0) {
// We have holidays, tell the user about them...
exclusions += " and the following holidays: ";
for(var i=0; i<results.holidays.length; i += 1){
exclusions += results.holidays[i]+", ";
}
} else {
// No holidays.
exclusions += ".";
}
$("#result").text(results.count + " business days." ).append("<p>("+exclusions+")</p>");
});
});
<div id="content">
<input type="text" class="myDateClass" id="startDate"/>
<input type="text" class="myDateClass" id="endDate"/>
<button id="calculateMe">How many business days?</button>
<div id="result"></div>
</div>
Fiddle
I spend a lot of time to format each highcharts elements to french format (texts, dates, buttons, etc..)
I propose a little "macro" french theme for your applications using highcharts.
Highcharts.theme = {
lang: {
/*------ Dates translation ------ */
months: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
weekdays: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi',
'Jeudi', 'Vendredi', 'Samedi'],
shortMonths: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil',
'Aout', 'Sept', 'Oct', 'Nov', 'Déc'],
/*------ Texts translation ------ */
downloadPNG: 'Télécharger en image PNG',
downloadJPEG: 'Télécharger en image JPEG',
downloadPDF: 'Télécharger en document PDF',
downloadSVG: 'Télécharger en document Vectoriel',
exportButtonTitle: 'Export du graphique',
loading: 'Chargement en cours...',
printButtonTitle: 'Imprimer le graphique',
resetZoom: 'Réinitialiser le zoom',
resetZoomTitle: 'Réinitialiser le zoom au niveau 1:1',
printChart: 'Imprimer le graphique',
/*------ Number Formate ------ */
thousandsSep: ' ', // ex: 52 000
decimalPoint: ',' // ex: 1 525,50
},
credits: {
/*------ Unrelated but usefull to remove credits in each charts ------ */
enabled: false
},
rangeSelector: {
/*------ Highstock date range selector (the 2 little inputs in right corner) ------ */
inputDateFormat: '%e %b %Y', // ex: 8 Avr 2014
inputEditDateFormat: '%d/%m/%Y', // After clicking on item ex : 13/06/2014
// Processing After enter key pressed : apply the 13/06/2014 format
inputDateParser: function (value) {
value = value.split('/');
return Date.UTC(
parseInt(value[2]),
parseInt(value[1]) - 1,
parseInt(value[0])
);
},
/*------ Highstock zoom selector (on the left top side) ------ */
buttons: [{
type: 'month',
count: 1,
text: '1 M' // useless translate :p
}, {
type: 'month',
count: 6,
text: '6 M' // useless translate :p
}, {
type: 'year',
count: 1,
text: '1 A' // translate Y in A (Année in french)
}, {
type: 'all',
count: 1,
text: 'Tout' // translate all in Tout
}],
selected: 2, // Here we force to select 6 M
inputEnabled: true // Active Inputs
},
};
Highcharts.setOptions(Highcharts.theme);
You have to add this file(charts-theme.js) between the highstock.js and your .highcharts function.
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://saur/assets/backend/pages/scripts/charts-theme.js"></script>
<script src="http://saur/assets/backend/pages/scripts/charts.js"></script>
Obviously, you can use it with different language, or just to define some "general" uses.
Hope it help.