Access Current System Time Zone - c#

Basically I can able to detect list of system time zones using following code:
foreach(TimeZoneInfo info in tz)
Debug.Log("time zone id : " + info.Id + " display name : " + info.DisplayName);
Running this code, I have following output in console.
In this list, I want to know, which one is my current system is following?
Because I want specific information about that time zone. As like in following code, I was written clear "Asia/Kolkata".
TimeZoneInfo infos = System.TimeZoneInfo.FindSystemTimeZoneById("Asia/Kolkata");
By running which code, I can able to get "Asia/Kolkata" as output?
EDIT: I was already using NodaTime here and code running for this purpose.
// Create a NodaTime DateTimeZoneSource object for IANA time zone names
var dateTimeZoneSource = TzdbDateTimeZoneSource.Default;
// Get the Windows time zone by name (or use TimeZoneInfo.Local)
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
// Convert between Windows and IANA time zone names
var tzdbTimeZoneInfo = dateTimeZoneSource.MapTimeZoneId(timeZoneInfo);
Console.WriteLine(tzdbTimeZoneInfo);
But in this, I am getting exception regarding,
Exception of type 'System.TimeZoneNotFoundException' was thrown.
I am using Mac system and editor as Mono Develop - Unity and my target devices are iPhones.

Using the code below you can get local TimeZoneInfo object.
TimeZoneInfo infos = TimeZoneInfo.Local;

Set your .NET API compatibility to 4.6. Here are the test results in my iOS device:
TimeZoneInfo.Local.Id
Editor: Local
iOS Device: Local
TimeZoneInfo.Local.DisplayName
Editor: Local
iOS Device: (GMT+03:30) Local Time
TimeZoneInfo.Local.StandardName
Editor: +0330
iOS Device: +0330
TimeZoneInfo.Local.DaylightName
Editor: +0430
iOS Device: +0430
TimeZoneInfo.Local.BaseUtcOffset.Hours + ":" + TimeZoneInfo.Local.BaseUtcOffset.Minutes);
Editor: 3:30
iOS Device: 3:30

maybe help u this links :
here
https://msdn.microsoft.com/en-us/library/gg154758.aspx
and
here
List of Timezone ID's for use with FindTimeZoneById() in C#?

Use this
TimeZoneInfo infos = TimeZoneInfo.FindSystemTimeZoneById(
{ "Asia/Kolkata", "India Standard Time" });
You can see this link for TimeZoneIds
http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html

On window Unity5.1.3 editor, TimeZoneInfo.GetSystemTimeZones() return empty list.
TimeZoneInfo.FindSystemTimeZoneById() and TimeZoneInfo.CreateCustomTimeZone() both raise System.TimeZoneNotFoundException.
but it work well in android device.
private static DateTime ToSeoulTime(DateTime dateUtc, bool ignoreUnspecified = false)
{
if (ignoreUnspecified == false && dateUtc.Kind == DateTimeKind.Unspecified)
{
if (UnityEngine.Application.isEditor)
{
throw new Exception("dateUtc.Kind == DateTimeKind.Unspecified");
}
else
{
UnityEngine.Debug.LogWarning("dateUtc.Kind == DateTimeKind.Unspecified");
}
}
try
{
var seoulTimezone = TimeZoneInfo.FindSystemTimeZoneById("Korea Standard Time");
return TimeZoneInfo.ConvertTime(dateUtc, seoulTimezone);
}
catch (System.TimeZoneNotFoundException e)
{
return new DateTime(dateUtc.AddHours(9).Ticks, DateTimeKind.Unspecified);
}
}

Update your player settings to use .NET 4.6

Related

How to get all enabled keyboard in xamarin.forms with C#

Good day,
in android phone -> virtual keyboard, system list all the enabled keyboards in this page, how can i get all enabled keyboards type with C# in my Xamarin.forms APP?
Thanks!
Roll
In Android, you could use InputDevice.
InputDevice: https://developer.android.com/reference/android/view/InputDevice
You could try the code below:
int[] devicesIds = InputDevice.GetDeviceIds();
foreach (var item in devicesIds)
{
//Check the device you want
InputDevice device = InputDevice.GetDevice(item);
//device.getName must to have virtual
var s = device.Name;
var b = device.KeyboardType;
}
You could use DependencyService to call this in Xamarin.Forms.
DependencyService: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction
thanks your reply, i try the way you suggested, but the returned value was not i want...
i found another post here, use that way and finally get the things i want,
here is my code to share:
InputMethodManager manager = (InputMethodManager)context.GetSystemService(Context.InputMethodService);
IList<InputMethodInfo> mInputMethodProperties = manager.EnabledInputMethodList;
IEnumerator<InputMethodInfo> imi = mInputMethodProperties.GetEnumerator();
while (imi.MoveNext())
{
InputMethodInfo inputInfo = imi.Current;
var iN = inputInfo.ServiceName;
}
Best Regards & thanks
Roll

can't load scores from leaderboard

i'm setting up a leaderboard system in my unity game, using the google play games services plugin.
i want to load score in order to integrate them in my custom LeaderbordUI,
I followed the documentation and used the ILeaderboard.LoadScores but it's not working.
when i check the logcat i get this :
02-04 11:03:56.580: W/Unity(18969): !!! [Play Games Plugin DLL] 02/04/19 11:03:56 +01:00 WARNING: Error returned from fetch: -108
I have tried to loadScore with the method "Social.LoadScores" and "PlayGamesPlatform.Instance.LoadScores", but i'm getting the same warning.
PS: when i use Social.ShowLeaderboardUI() it shows me the leaderboard.
but when i use PlayGamesPlatform.Instance.ShowLeaderboardUI(LB_Stars.id) to show a specific leaderboard it gives me "hmm,something went wrong in play games"
public void LoadLeaderboard()
{
LB_Stars.LoadScores(ok =>
{
if (ok)
{
LoadUsersAndDisplay(LB_Stars);
}
else
{
Debug.Log("Error retrieving STARS leaderboard");
}
});
}
internal void LoadUsersAndDisplay(ILeaderboard lbStar)
{
Debug.Log("gonna load user and display them");
List<string> userIds = new List<string>();
foreach (IScore score in lbStar.scores)
{
userIds.Add(score.userID);
}
Social.LoadUsers(userIds.ToArray(), (users) =>
{
string status = "Leaderboard loading: " + lbStar.title + " count = " +
lbStar.scores.Length;
foreach (IScore score in lbStar.scores)
{
IUserProfile user = FindUser(users, score.userID);
if (user != null)
{
UserLeaderboardClone = Instantiate(UserLeaderboardPrefab);
UserLeaderboardClone.name = score.rank.ToString();
LeaderboardUserScript lbUser = UserLeaderboardClone.GetComponent<LeaderboardUserScript>();
lbUser.transform.SetParent(LBScrollview.content.transform, false);
FillUserInfo(lbUser, user, score);
}
}
});
}
Okay i've figured it out, based on a comment on github https://github.com/playgameservices/play-games-plugin-for-unity/issues/2045#issuecomment-350335234
After spending a couple of hours on this, my problem turned out to be my game was using leaderboard ids from another app.
So it failed with this "unauthorized error", however the exact cause was not given.
The reason why it happened was because the play games configuration in unity was caching old values. When you open it - it has the correct ids, however in the generated GPGSids.cs file - wrong ids are present.
The solution was simply to regenerate that by re-saving the configuration.

Convert Gmail Date to your DateTime as displayed in Gmail Account

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

Same code but getting different result

When I use below code I am getting different result on my developer pc and my remote server.
string _QsDateTime = "12.11.2016 21:30";
var _CountryZone = DateTimeZoneProviders.Tzdb["TUR"];
var _DatePattern = LocalDateTimePattern.CreateWithCurrentCulture("yyyy-MM-dd HH:mm:ss");
var _LocalTime = _DatePattern.Parse(_QsDateTime).Value;
var _LocalTime2TargetZoneTime = _LocalTime.InZoneStrictly(_CountryZone);
var _TargetZone2Utc = _LocalTime2TargetZoneTime.WithZone(DateTimeZone.Utc).ToDateTimeUtc();
_QsDateTime = _TargetZone2Utc.ToString("yyyy-MM-dd HH:mm:ss");
Developer PC result is: "2016-11-12 19:30:00"
Remote server result is: "2016-12-11 19:30:00"
Remote server specs is Windows 2012 server English Developer PC specs is Windows 7 Turkish but both of them regional date time setting are same.
Why I am getting different result?
I'm not too much familiar with Noda Time but I have a few things to say:
DateTimeZoneProviders.Tzdb does not have a time zone identifier as TUR as far as I know, you should use Europe/Istanbul instead.
When you create a LocalDateTimePattern with CreateWithCurrentCulture method, it uses current culture settings and these are different in your both server. Be careful about that.
LocalDateTimePattern.Parse method use the rules of the current pattern. Your string is 12.11.2016 21:30 but your pattern is yyyy-MM-dd HH:mm:ss. You see my point, don't you?
If you really get different results in your servers, you shouldn't blame your last line since both en-US and tr-TR cultures uses GregorianCalendar as a Calendar property and that doesn't effect the result. You might wanna check LocalDateTimePattern.Parse method line instead.
For example;
using System;
using NodaTime;
using NodaTime.Text;
public class Program
{
public static void Main()
{
string _QsDateTime = "12.11.2016 21:30";
var _CountryZone = DateTimeZoneProviders.Tzdb["Europe/Istanbul"];
var _DatePattern = LocalDateTimePattern.CreateWithCurrentCulture("dd.MM.yyyy HH:mm");
var _LocalTime = _DatePattern.Parse(_QsDateTime).Value;
var _LocalTime2TargetZoneTime = _LocalTime.InZoneStrictly(_CountryZone);
var _TargetZone2Utc = _LocalTime2TargetZoneTime.WithZone(DateTimeZone.Utc).ToDateTimeUtc();
_QsDateTime = _TargetZone2Utc.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(_QsDateTime);
}
}
generates
2016-11-12 19:30:00
Here a demonstration.

iCal Time Zone issue

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).

Categories