I am getting inbox messages using Gmail API in my c# ASP.net application. All messages are from different time zones(states/countries), I wanna display there date in my own time zone as it displays in Gmail App. I searched a lot for conversion between timezones but can't solve it may be i am not getting it properly.
My code for but i tried so far is: (Its working for most of messages but for few of them its not displaying right DateTime)
For Example:
Time displayed in Gmail App: 30/11/2017 2:11 AM
My code Input/ value from Gmail API: Wed, 29 Nov 2017 10:11:35 -0800
Below are some values i am getting from my current gmail inbox messages:
var re = service.Users.Messages.List("me");
re.LabelIds = "INBOX";
re.Q = "is:all";
var res = re.Execute();
if (res != null && res.Messages != null)
{
foreach (var email in res.Messages)
{
var emailInfoResponse = service.Users.Messages.Get("me", email.Id).Execute();
if (emailInfoResponse != null)
{
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
if (mParts.Name == "Date")
{
date = mParts.Value;
}
}
}
}
}
My Time Zone is: (UTC+08:00) Perth
Any help would be appreciated. Thanks!
{
"id": string,
"threadId": string,
....
"internalDate": long,
"payload": {
....
internalDate long
The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For normal SMTP-received email, this represents the time the message was originally accepted by Google, which is more reliable than the Date header. However, for API-migrated mail, it can be configured by client to be based on the Date header.
REF: https://developers.google.com/gmail/api/v1/reference/users/messages
Based on the above Google documentation, here's one way:
//Some epoch time in ms
var gmail_date = 1512007768005;
//Get DateTime of epoch ms
var to_date = DateTimeOffset.FromUnixTimeMilliseconds(gmail_date).DateTime;
//This is your timezone offset GMT +8
var offset = 8;
Console.WriteLine(to_date - new TimeSpan(offset *-1, 0, 0));
Gets you 11/30/2017 10:09:28 AM
Related
Newbie here, need to get a DateTime value for when each email was originally received.
EDIT: Added code. I have the item, I am just trying to get the time received but I cannot find the property for it.
foreach (MailItem item in mailItems)
{
emailDetails = new OutlookEmails
{
EmailFrom = item.SenderEmailAddress,
EmailSubject = item.Subject,
EmailBody = item.Body
};
listEmailDetails.Add(emailDetails);
ReleaseComObject(item);
}
item.ReceivedTime is the answer.
Credit to:
user1011627
I am trying to do a UWP app that changes wallpaper and lockscreen based on the time of the day (as a start). I am facing difficulties implementing this:
I have the task "SetWallpaperAsync" on main page (I am making sure it works before shifting it to a background task) as fallowing:
private async Task<bool> SetWallpaperAsync()
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
var imageID = DateTime.Now.Hour.ToString("HH");
var uri = new Uri($"ms-appx:///Dynamic/Dynamic-{imageID}.jpg");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file);
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file);
}
return success;
}
But it only worked once then it stopped, which lead me to believe that the imageID string is not returning the correct value (the value is between 00 and 23, corresponding to the hours in a day in a 24 format).
I have also tried to link a textblock to the same value and different formats, but it did not appear on the app homepage. I am not sure at all where its going wrong!
// Time format
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("hour");
DateTime dateToFormat = DateTime.Now;
var mydate = formatter.Format(dateToFormat);
TimeDescriptionTextBlock.Text = mydate.ToString();
// another try with the time
TimeHours.Text = DateTime.Now.ToString("HH:mm:ss");
How can I debug this code and see where its stopping?
If you output the imageID variable in the Output windows using Debug.Writeline:
var imageID = DateTime.Now.Hour.ToString("HH");
Debug.WriteLine(imageID);
You can see that the output is: HH.
The reason for this is that the format string HH works on DateTime variables, but you are actually calling it on the Hour variable only, which is just a number.
There are two possible solutions:
Remove the .Hour from the call: var imageID = DateTime.Now.ToString("HH");
Just use the Hour as a number: var imageID = DateTime.Now.Hour.ToString();
Both solutions are equivalent and will yield a 24-hour format hour number.
I'm trying to take events from Google Calendar and display them in a listView for Xamarin.Forms.
Google Calendar uses an RFC3339 format when you call start.dateTime the format is yyyy-mm-dd.
I'm trying to do a string day of the week format (Mon Jan 1, 2018) similar to .Net DateTime.ToLongDateString Method.
My Code so far is this:
namespace TheFirstAcademy.ViewModels{
class EventListViewModel
{
public List<SchoolEvent> SchoolEvents { get; set; }
public SchoolCalendar SelectedCalendar { get; set; }
public EventListViewModel(SchoolCalendar selectedcalendar)
{
SelectedCalendar = selectedcalendar;
SchoolEvents = GetSchoolEvents();
}
public List<SchoolEvent> GetSchoolEvents()
{
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
ApiKey = "Key",
ApplicationName = "TFA Calendar Mobile App",
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List(SelectedCalendar.SchoolCalId);
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// List events.
Events events = request.Execute();
List<SchoolEvent> schoolEvents = new List<SchoolEvent>();
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
schoolEvents.Add(new SchoolEvent() {
EventTitle = eventItem.Summary,
EventDescription = eventItem.Description,
EventStartTime = when,
EventEndTime = eventItem.End.Date
});
}
}
return schoolEvents;
}
}
}
This will eventually get displayed in a ListView for iOS and Android using Xamarin.Forms. The Event for a calendar would look something like this:
[Event Name]
[Event Location]
Starts: Fri May 25, 2018 12:00 PM
Ends: Sat May 26, 2018 12:00 PM
Some references I have been found:
Google Calendar v3 Events info
https://developers.google.com/calendar/v3/reference/events
RFC to dateTime (not sure if this is the right direction).
How do I parse and convert a DateTime to the RFC 3339 date-time format?
Any help is appreciated.
I figured out the conversion by using. DateTime.Parse()
I converted the eventItem.Start.Date (which is a string)to DateTime using DateTime.Parse(). Then I converted the DateTime to string ("ddd MMM dd, yyyy").
Probably basic stuff Maybe this will help someone.
I am using ical.net to provide outlook internet calendar integration for my solution.
I have several events from 00:00 a.m. to 00:00 a.m. (next day).
When I add an alarm to the events, in Outlook these events show with no alert.
This is the code how I added the alarms and events.
foreach (var taskItem in taskItems.Where(t => t.DueDate != null && t.DueDate.HasValue == true))
{
var hyperlink = Request.GetBaseUrl();
hyperlink = string.Format("{0}/TaskBoard/Tasks?listId={1}", hyperlink, taskItem.ListId);
var dueDate = new DateTime(taskItem.DueDate.Value.Ticks, DateTimeKind.Utc);
var alarm = new Alarm()
{
Summary = taskItem.Title,
Trigger = new Trigger(TimeSpan.FromMinutes(-15)),
Action = AlarmAction.Display
};
var calendarEvent = new Event
{
Class = "PUBLIC",
Summary = taskItem.Title,
Created = new CalDateTime(taskItem.Created.Value),
Description = string.Format("Open board: {0}", hyperlink),
Start = new CalDateTime(dueDate),
End = new CalDateTime(dueDate.AddDays(1)),
Uid = taskItem.Id.ToString(),
Location = taskItem.ListTitle
};
calendarEvent.Alarms.Add(alarm);
calendar.Events.Add(calendarEvent);
}
this is the resulting iCal file content
BEGIN:VCALENDAR
PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 2.2//EN
VERSION:2.0
X-WR-CALNAME:Agile Kanban - Meine Aufgaben
BEGIN:VEVENT
CLASS:PUBLIC
CREATED:20170814T114839
DESCRIPTION:Open board: https://localhost:44300/TaskBoard/Tasks?listId=637
90e98-cacc-4f03-992f-f3276db06dda
DTEND:20170827T220000Z
DTSTAMP:20170829T170757Z
DTSTART:20170826T220000Z
LOCATION:Room1
SEQUENCE:0
SUMMARY:Task changed
UID:1d4b10bf-7434-41d9-8dd2-311e3679b0a7
BEGIN:VALARM
ACTION:Display
SUMMARY:Task changed
TRIGGER:-PT15M
END:VALARM
END:VEVENT
END:VCALENDAR
How are the event added to Outlook ?
If they are made available as an http subscription, Outlook is probably ignoring it on purpose. How one wants to be notified in advance is a really a personal choice so calendar clients tend to ignore alarms from outside sources, whether added via an invitations (see Sent email with iCal to outlook with valarm reminder ) or via public calendar subscriptions.
If you are doing an import of the task and the alarms still do not show up, there might be a problem with your iCalendar stream so seing the actual iCalendar stream instead of your code would be more useful.
Finally, I vaguely remember Outlook handling only absolute alarms (see https://www.rfc-editor.org/rfc/rfc5545#section-3.8.6.3) for VTODO but I do not know whether it is still the case.
I'm trying to allow a user to download an iCal for their calendar in ASP.Net, but am having a timezone issue.
If I download the file on my computer, the time appears correct and within the correct timeframe. However, when I try to download it on a phone, the timezone switches and it becomes 5 hours behind (aka 7:00 AM becomes 3:00 AM).
Does anyone know how to fix this issue/set the timezone?
Here is the code:
iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
DateTime dt = (DateTime)Convert.ToDateTime(lblTicketDue.Text);
Console.Write(dt);
evt.Start = new iCalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
evt.End = new iCalDateTime((DateTime)Convert.ToDateTime(lblTicketDue.Text).AddMinutes(15.0));
Alarm alarm = new Alarm();
alarm.Action = AlarmAction.Display;
alarm.Summary = "Ticket due!";
Trigger t = new Trigger();
iCalDateTime icdt = new iCalDateTime(dt.Subtract(TimeSpan.FromMinutes(120.0)));
t.DateTime = icdt;
alarm.Trigger = t;
evt.Alarms.Add(alarm);
iCal.Events.Add(evt);
iCalendarSerializer serializer = new iCalendarSerializer();
string output = serializer.SerializeToString(iCal);
Response.ContentType = "text/calendar";
Response.Write(output);
Response.End();
Hard to tell without looking at the actual iCalendar stream that gets generated but it is quite likely that you are generating your DTSTART/DTEND using floating time (e.g. "20160517T070000" ).
If the event is not recurring (no RRULE), what you want to do is convert your datetime to UTC and use the "date with UTC time" format described in https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5
i.e. something like "20160517Txx0000Z"
If the event is recurring you would then need to use the last form (date with local time and timezone reference).