如何比较 javascript 上的时间?
How compare time on javascript?
我正在尝试比较用户输入的星期几和用户选择的小时,但它不起作用。第一个问题是,dialogflow 只接受时间 AM 和 PM,而不是 24 小时格式(我试图使用时刻 JS,但也没有成功......),第二个问题是我的条件不起作用,即使我提出所有这些条件,机器人也会进行预约。
对不起我的英语,有人可以帮助我吗? :/
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
});
// Enter your calendar ID below and service account JSON below
// Starts with {"type": "service_account",...
// Set up Google Calendar Service account credentials
const serviceAccountAuth = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: 'https://www.googleapis.com/auth/calendar'
});
const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
const timeZone = 'America/Buenos_Aires';
const timeZoneOffset = '-03:00';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log("Parameters", agent.parameters);
const appointment_type = agent.parameters.especialidade;
function makeAppointment (agent) {
// Calculate appointment start and end datetimes (end = +1hr from start)
//console.log("Parameters", agent.parameters.date);
const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
const appointmentTimeString = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
);
return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type).then(() => {
agent.add(`Ok, ${appointmentTimeString} is fine!.`);
}).catch(() => {
agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
});
}
let intentMap = new Map();
intentMap.set('marcarconsultas', makeAppointment);
agent.handleRequest(intentMap);
});
function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type) {
var time = dateTimeStart.getHours();
var weekly = dateTimeStart.getDay();
//adjust timezone
return new Promise((resolve, reject) => {
calendar.events.list({
auth: serviceAccountAuth, // List events for time period
calendarId: calendarId,
timeMin: dateTimeStart.toISOString(),
timeMax: dateTimeEnd.toISOString()
}, (err, calendarResponse) => {
// Check if there is a event already on the Calendar
if (err || calendarResponse.data.items.length > 0) {
reject(err || new Error('Requested time conflicts with another appointment'));
} else if (err || time > 17) {
reject(err || new Error('We are open until 17h'));
} else if (err || time < 8) {
reject(err || new Error('We open at 8h'));
} else if (err || weekly == 0 && weekly == 6) {
reject(err || new Error('We do not work saturday or sunday'));
} else if (err || appointment_type == 'cardiologia' || (time < 8 && time > 12) && (weekly != 4)) {
reject(err || new Error ('Choose an hour between 8h and 12h'));
} else if (err || appointment_type == 'infectiologia' || (time < 10 && time > 14) && (weekly == 5)) {
reject(err || new Error ('Choose an hour between 10h and 14h'));
} else if (err || appointment_type == 'pré-natal' || ( time < 14 && time > 17) && (weekly != 3)) {
reject(err || new Error ('Choose an hour between 14h and 17h'));
} else if (err || appointment_type == 'angiologia' || (time < 8 && time > 12) && (weekly != 3)) {
reject(err || new Error('Choose an hour between 8h and 12h'));
} else if (err || appointment_type == 'otorrinolaringologia' || (time < 8 && time > 17) && (weekly != 2 && weekly != 4)) {
reject(err || new Error('Choose an hour between 8h and 17h'));
}
else {
// Create event for the requested time period
calendar.events.insert({ auth: serviceAccountAuth,
calendarId: calendarId,
resource: {summary: appointment_type +' Appointment', description: appointment_type,
start: {dateTime: dateTimeStart},
end: {dateTime: dateTimeEnd}}
}, (err, event) => {
err ? reject(err) : resolve(event);
}
);
}
});
});
}
如果你想转换成 am pm 试试这个函数
getTime(timestamp) {
var date = new Date(timestamp * 1000);
var hour = date.getHours();
var minute = date.getMinutes();
var dayOrNight = false;
if (hour > 12) {
hour = hour - 12;
dayOrNight = true;
} else if (hour === 12) {
dayOrNight = true;
} else if (hour === 0) {
hour = 12;
dayOrNight = false;
} else {
dayOrNight = false;
}
if (minute < 10) {
minute = `0${minute}`;
}
var AMPM = dayOrNight ? "PM" : "AM";
return `${hour}:${minute} ${AMPM}`;
}
你能告诉我们什么是用户输入以及你将其与哪些数据进行比较
我认为您可以在转换 toLocaleString
时使用 hour12: false
或 hour12: true
选项来搞乱时间,在 MozillaWebDocs.
中提到
const timeZone = 'America/Buenos_Aires';
const dateTimeStart = new Date();
var hour12 = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone, hour24: true }
);
var hour24 = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone, hour12: false }
);
console.log(hour24)
console.log(hour12)
我正在尝试比较用户输入的星期几和用户选择的小时,但它不起作用。第一个问题是,dialogflow 只接受时间 AM 和 PM,而不是 24 小时格式(我试图使用时刻 JS,但也没有成功......),第二个问题是我的条件不起作用,即使我提出所有这些条件,机器人也会进行预约。 对不起我的英语,有人可以帮助我吗? :/
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
});
// Enter your calendar ID below and service account JSON below
// Starts with {"type": "service_account",...
// Set up Google Calendar Service account credentials
const serviceAccountAuth = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: 'https://www.googleapis.com/auth/calendar'
});
const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
const timeZone = 'America/Buenos_Aires';
const timeZoneOffset = '-03:00';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log("Parameters", agent.parameters);
const appointment_type = agent.parameters.especialidade;
function makeAppointment (agent) {
// Calculate appointment start and end datetimes (end = +1hr from start)
//console.log("Parameters", agent.parameters.date);
const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
const appointmentTimeString = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
);
return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type).then(() => {
agent.add(`Ok, ${appointmentTimeString} is fine!.`);
}).catch(() => {
agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
});
}
let intentMap = new Map();
intentMap.set('marcarconsultas', makeAppointment);
agent.handleRequest(intentMap);
});
function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type) {
var time = dateTimeStart.getHours();
var weekly = dateTimeStart.getDay();
//adjust timezone
return new Promise((resolve, reject) => {
calendar.events.list({
auth: serviceAccountAuth, // List events for time period
calendarId: calendarId,
timeMin: dateTimeStart.toISOString(),
timeMax: dateTimeEnd.toISOString()
}, (err, calendarResponse) => {
// Check if there is a event already on the Calendar
if (err || calendarResponse.data.items.length > 0) {
reject(err || new Error('Requested time conflicts with another appointment'));
} else if (err || time > 17) {
reject(err || new Error('We are open until 17h'));
} else if (err || time < 8) {
reject(err || new Error('We open at 8h'));
} else if (err || weekly == 0 && weekly == 6) {
reject(err || new Error('We do not work saturday or sunday'));
} else if (err || appointment_type == 'cardiologia' || (time < 8 && time > 12) && (weekly != 4)) {
reject(err || new Error ('Choose an hour between 8h and 12h'));
} else if (err || appointment_type == 'infectiologia' || (time < 10 && time > 14) && (weekly == 5)) {
reject(err || new Error ('Choose an hour between 10h and 14h'));
} else if (err || appointment_type == 'pré-natal' || ( time < 14 && time > 17) && (weekly != 3)) {
reject(err || new Error ('Choose an hour between 14h and 17h'));
} else if (err || appointment_type == 'angiologia' || (time < 8 && time > 12) && (weekly != 3)) {
reject(err || new Error('Choose an hour between 8h and 12h'));
} else if (err || appointment_type == 'otorrinolaringologia' || (time < 8 && time > 17) && (weekly != 2 && weekly != 4)) {
reject(err || new Error('Choose an hour between 8h and 17h'));
}
else {
// Create event for the requested time period
calendar.events.insert({ auth: serviceAccountAuth,
calendarId: calendarId,
resource: {summary: appointment_type +' Appointment', description: appointment_type,
start: {dateTime: dateTimeStart},
end: {dateTime: dateTimeEnd}}
}, (err, event) => {
err ? reject(err) : resolve(event);
}
);
}
});
});
}
如果你想转换成 am pm 试试这个函数
getTime(timestamp) {
var date = new Date(timestamp * 1000);
var hour = date.getHours();
var minute = date.getMinutes();
var dayOrNight = false;
if (hour > 12) {
hour = hour - 12;
dayOrNight = true;
} else if (hour === 12) {
dayOrNight = true;
} else if (hour === 0) {
hour = 12;
dayOrNight = false;
} else {
dayOrNight = false;
}
if (minute < 10) {
minute = `0${minute}`;
}
var AMPM = dayOrNight ? "PM" : "AM";
return `${hour}:${minute} ${AMPM}`;
}
你能告诉我们什么是用户输入以及你将其与哪些数据进行比较
我认为您可以在转换 toLocaleString
时使用 hour12: false
或 hour12: true
选项来搞乱时间,在 MozillaWebDocs.
const timeZone = 'America/Buenos_Aires';
const dateTimeStart = new Date();
var hour12 = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone, hour24: true }
);
var hour24 = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone, hour12: false }
);
console.log(hour24)
console.log(hour12)