-4

I want to know how many seconds are passed since 1970/1/1 till today's 9am PST. How can I do that in C#?

I need this in front end application, where every device can have different time zone. But in anyways, I need seconds elapsed from current day's 9am PST time zone.

  • This is not a duplicate, as my problem is with Time Zone. – Narek Aghekyan Jul 11 '18 at 11:03
  • They are the same. Because every PST as Utc Equivalent. DateTime are etiher Unspecified, Local, or Utc. You should just keep everything in Utc and convert with the Timezone Info when display in timezone is needed. – Drag and Drop Jul 11 '18 at 11:29

2 Answers2

0

If your server is set to use PST time then you could do the following

Goes like this:

  TimeSpan test = DateTime.Now - new DateTime(1970, 01, 01);
  MessageBox.Show(test.TotalSeconds.ToString());

For one liner:

 MessageBox.Show((DateTime.Now - new DateTime(1970, 01, 01))
     .TotalSeconds.ToString());

If you can not guarantee that PST is being used on the computer your code will run you can declare the timezone like this

var zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var utcNow = DateTime.UtcNow;
var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, zone);
MessageBox.Show((pacificNow  - new DateTime(1970, 01, 01))
     .TotalSeconds.ToString());

Hope this helps

Fuzzybear
  • 1,388
  • 2
  • 25
  • 42
  • Please see my question. I have added details. – Narek Aghekyan Jul 11 '18 at 11:02
  • @PaulF it is not duplicate. NOTE the TIme Zone. – Narek Aghekyan Jul 11 '18 at 11:04
  • @NarekAghekyan : not me who marked it as duplicate - just commenting on the fact that the answer was a direct cut & paste from that answer & not attributed to the original poster. – PaulF Jul 11 '18 at 11:37
  • @Fuzzybear thank you for your answer, but it converts my time to PST time zone. What I want is today's PST 9am converted to epoch. – Narek Aghekyan Jul 11 '18 at 12:46
  • If you are just after 9am PST today in epoch time then input that as the value for pacificNow... are you looking to do this every day.. ie tomorrow you want epoch time from tomorrow 9am? – Fuzzybear Jul 11 '18 at 12:58
0
    TimeZoneInfo destTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
    int timeZoneDiffSeconds = (int) destTimeZone.BaseUtcOffset.Subtract(TimeZoneInfo.Local.BaseUtcOffset).TotalSeconds;

    DateTime todayLocal9Am = DateTime.Today.Date + new TimeSpan(9, 0, 0);

    Int32 unix9AmLocalTime = (Int32) (todayLocal9Am.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    Int32 unix9AmPstTime = unix9AmLocalTime - Math.Abs(timeZoneDiffSeconds);

    Console.WriteLine(unix9AmPstTime);

    Console.Read();
Mojtaba Tajik
  • 1,725
  • 16
  • 34