Searching emails in gmail based on time - gmail

I want a list of all yesterday's emails from gmail. I am trying to process it using google apps script, by writing a query on my inbox, and then using GmailApp.search. The after: and before: search query in gmail returns results that are not expected, since the query searches on the basis of the SMTP server time that the mail is sent from (which is google's server). Hence, being in a different time zone, the search yields inappropriate results to me. Is there a way to search gmail using a time criteria, so that I can accommodate for the time zone difference?
Please note that the local time zone, calendar, gmail etc. is correctly configured for my timezone, so the emails that I see in my inbox are correctly timed. Only the search is creating an issue.

Figured out a way after some trial and error, that it is indeed possible to search gmail emails by time. Notice that the Date() returned in google apps script is according to your timezone.
The code below will return all previous day's emails in inbox, assuming new Date() is giving the date and time according to your timezone. Division by 1000 is done because getTime() returns milliseconds, while the newer / older search query expects seconds.
var month = new Date().getMonth();
var date = new Date().getDate();
var year = new Date().getFullYear();
var time1 = new Date(year, month, date, 0, 0, 0).getTime();
var time2 = time1 - 86400000;
var query = "newer:" + time2/1000 + " older:" + time1/1000 + " in:inbox";
var conversations = GmailApp.search(query);

Can you give the exact search string you are using along with how you construct the before and after dates ?
You can use the Utilities.formatDate() function to format the date string to the timezone you are in.
An alternate solution is to fetch all mails (maybe a 100 or so) and then discard all those which do not fit in the time period you are interested in.

Related

Saved Search with Time Criteria

Use-Case : I am having an Integration in place that creates multiple Vendor Bills in Netsuite for every 5 minutes. I want to export the vendor bills created in those time to FTP. For that I need to create a saved search that can preview vendor bills created in past five minutes. Do we have any criteria in Netsuite Save Search to accomplish that ?
Please advise.
A Netsuite inconsistency.
I keep a snippet for this.
function toNSLegalDatetime(date){
var formatted = <string>format.format({value:date, type:format.Type.DATETIMETZ});
return formatted.replace(/(:\d{2}):\d{2}/, '$1');
}
Then you can do:
const lastDT = new Date(Date.now() - 5*60000)); // 5 minutes ago
search.create({
type:'vendorbill',
filters:[
search.createFilter({name:'datecreated', operator:search.Operator.ONORAFTER, values:toNSLegalDatetime(lastDT)}),
...
BUT
timing like this is very tricky because small delays in timing could cause you to miss transactions. If you can keep track of the last internalid reported your next search could just use that and it wouldn't matter what the lag was.
search.createFilter({name:'internalidnumber', operator:search.Operator.GREATERTHAN, values:lastIdReported})

Google Ads API - How to get all campaigns that are created via google ads api (Node JS)

I am trying to find the total cost of google ads campaigns that are created via a particular manager account or via google ads api.
I tried the change event query where it gives me all the campaigns created via google ads but the issue is with change_event.change_date_time. It requires this filter otherwise it throws an error. Because of this filter, I am only getting campaigns that are created in this specific time period, but I need all campaigns.
SELECT
change_event.campaign
FROM change_event
WHERE
campaign.status != 'REMOVED'
AND change_event.change_date_time >= '${from_date}'
AND change_event.change_date_time <= '${to_date}'
AND change_event.client_type = 'GOOGLE_ADS_API'
ORDER BY change_event.change_date_time ASC
LIMIT 10000
Reference Link: https://developers.google.com/google-ads/api/fields/v9/change_event_query_builder
Unfortunately, change_event can only go retrieve data up to 30 days old (see here).
I've tried building a query that could get that information but using FROM campaign but it seems like only change_event has access to how a campaign was created.
A possible solution would be to create multiple from/to date on 30-day cycles, starting from the account creation date.
Otherwise, you can use change status for a slightly larger window of 90 days, with the limitation that you can't filter by change_event.client_type = 'GOOGLE_ADS_API', using simply change_status.resource_status = 'ADDED' instead.
SELECT
change_status.campaign
FROM change_status
WHERE
campaign.status != 'REMOVED'
AND change_status.resource_status = 'ADDED'
AND change_status.last_change_date_time >= '${from_date}'
AND change_status.last_change_date_time <= '${to_date}'
ORDER BY change_status.last_change_date_time ASC
LIMIT 10000

Dialogflow can't handle shortforms for #sys.date

So I am making a bot that tells the user my shop's operating hours. The code works but the problem is, Dialogflow can't seem to recognize shortforms like 'next sat', 'on mon', 'ltr', 'tmr'. I tried using custom entities but I can't tell Dialogflow to recognize the custom entity as a system parameter like #sys.date, and I'm having trouble extracting the dates from phrases like these. I could hard code it, for example
var date = new Date();
var short = agent.parameters.shortform;
var day = date.getDay();
if (short == 'tmr'){
if(day==6){day=0;}else{day+=1;}
}
but if I do this, I'd have to take into account every possible shortform my user can write and write code for it, including every day of the week, every other shortform like nxt, ltr, hrs, mins. Is there an easier way?

How to get the local timezone from the system using nodejs

Is there a way to obtain the local timezone from the system (eg:- ubuntu) using nodejs?
I used moment.js to extract the date and time values. But couldn't find a way to extract the timezone as well.
The existing answers will tell you the current timezone offset, but you will have issues if you are comparing historic/future points in time as this will not cater for daylight saving changes.
In many timezones, the offset varies throughout the year and these changes occur at different dates or not at all depending on the latitude. If you only have UTC time and an offset, you can never be sure what the offset will be in that location at various other times during the year.
For example, a UTC+2:00 offset could refer to Barcelona in the summer or Ivory Coast all year round. The 2hr offset will always display the correct time in Ivory Coast but will be 1hr out for half the year in Barcelona.
Check out this great article covering the above.
How do we cater for all these time zone issues? Well, it's pretty simple:
Save all times in UTC
Store the time zone string for where this event occurred
In modern browsers or node.js, you can get the local IANA time zone string like this:
Intl.DateTimeFormat().resolvedOptions().timeZone // eg. 'America/Chicago'
You can then use this timezone string in a library like Luxon to help offset your captured UTC times.
DateTime.fromISO("2017-05-15T09:10:23", { zone: "Europe/Paris" });
It is very simple.
var x = new Date();
var offset= -x.getTimezoneOffset();
console.log((offset>=0?"+":"")+parseInt(offset/60)+":"+String(offset%60).padStart(2, "0"))
And there is nothing else or you can see if momentJS can help you or not.
Note: This answer is outdated, you can suggest to add in it.
It is this easy, no libraries needed:
console.log("test ...")
let d = new Date()
console.log("UTC time " + d)
let ank = d.toLocaleString('en-US', { timeZone: 'America/Anchorage' });
console.log("your time zone " + ank)
How to see the exact time zone names on most servers:
ls /usr/share/zoneinfo
Works flawlessly:
You'll get the correct time-text regardless of daylight savings issues, etc etc.
Handy related mysql tip:
On almost all servers, mysql also needs to know the tz info.
Basically the solution is, on the shell
sudo mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql
.. google more about it.
I solved this using moment.js (http://momentjs.com/docs/)
var moment = require('moment');
var offset = moment().utcOffset();
console.log(''.concat(offset < 0 ? "-" : "+",moment(''.concat(Math.abs(offset/60),Math.abs(offset%60) < 10 ? "0" : "",Math.abs(offset%60)),"hmm").format("HH:mm")));
------Edited--------
I found a better solution using moment.js. Just use moment().format('Z')
which gives the output :
+05:30

Reminder Service in C#.Net 4.0 using UTC Time

I have a Windows Service that runs on my
Texas origin Server Central Time.
This will check for all active reminders and compares the reminder time that user wants and send out reminder if it matches with user required time.
Scenarios
User is from EST
User set up a reminder for *1:25 PM * using UI via my website
On submit, my C# business logic converts this time to UTC before storing in my database. That will become '18:25:00'
My Business logic will pull all Active reminders from DB
And checks for reminder time if current UTC time and Reminder setup time diffrence is less then 5 mins, then it will send notification to that customer.
this is how my logic written
DateTime CurrentDate = DateTime.Now.ToUniversalTime();
TimeSpan currentTime = DateTime.Now.ToUniversalTime().TimeOfDay;
if (Reminder.DailyReminders.Any(x => currentTime.Subtract(x.ReminderTime).TotalMinutes < 5
&& currentTime.Subtract(x.ReminderTime).TotalMinutes > 0))
{
if (Reminder.ReminderMedhodID.Equals(1))
_email.ComposeEmail(Reminder);
}
My Problem is
*currentTime* is always 1 hour behind to user requested reminder time SO my reminders are going out 1 hour late.
Note : currentTime is from below
TimeSpan currentTime = DateTime.Now.ToUniversalTime().TimeOfDay;
I am not sure if this is the best way to handle this requirement. considering this is one of the way, can any on help how to fix this issue?
Thanks to peter's answer
Can any one help me how to take user input time with Daylight consideration
This what i have so far
public TimeSpan ConvertToUTCTime(string dateStr)
{
DateTime localDateTime = DateTime.Parse(dateStr); // Local .NET timeZone.
DateTime utcDateTime = localDateTime.ToUniversalTime();
string clTimeZoneKey = TimeZone.CurrentTimeZone.StandardName;
TimeZoneInfo clTimeZone = TimeZoneInfo.FindSystemTimeZoneById(clTimeZoneKey);
DateTime clDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, clTimeZone);
if (clTimeZone.IsDaylightSavingTime(localDateTime))
{
// Get DayLight local time in UTC
// Yet to be implemented
}
return clDateTime.TimeOfDay;
}
I got this worked using this
http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx
Ummm...we are currently using Daylight Saving Time in most of the U.S. (though there are some portions of Indiana that did/do use EST?) Since EDT is one hour ahead of EST, your logic is correct. It is the input (EST) that is incorrect.

Resources