-2

I stored datetime into database then i retrieve the values.. My server db is located other country. so when the value is retrieve it is taking other country date and time..

I tried in controller as follow,

 if (item.CreatedDate == null)
        {
            item.CreatedDate = DateTime.Now;
            var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.CreatedDate, TimeZoneInfo.Local.Id, item.CreatedDate.Value).ToString();
        }

I got line error here... How to correct it?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
PoliDev
  • 1,408
  • 9
  • 24
  • 45

1 Answers1

2

You're passing values that aren't even of the right data type. Read up on TimeZoneInfo so you know how to use it properly.

Also read:

Also understand that somewhere here you actually have to know the user's time zone. Just calling TimeZoneInfo.Local.Id isn't going to work, because that is also the server's time zone. There's no magic performed by MVC to know the time zone of your user. You'll have to ask them for it, or employ some other strategy involving JavaScript.

From your comments, it appears you are looking for something like this:

// These should be stored in UTC.  Do not store them in anyone's local time.
item.CreatedDate = DateTime.UtcNow;
item.UpdatedDate = DateTime.UtcNow;

// Then later when you want to convert to a specific time zone, do this
string timeZoneId = "India Standard Time"; // as an example
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime localCreated = TimeZoneInfo.ConvertTimeFromUtc(item.CreatedDate, timeZone);
DateTime localUpdated = TimeZoneInfo.ConvertTimeFromUtc(item.UpdatedDate, timeZone);

Also, it seems like you might be using DateTime? (nullable datetimes) for your properties. It doesn't make sense to do that for these fields. They should be non-null in your database and always contain a value.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.UpdatedDate.Value, TimeZoneInfo.Local.Id, "India Standard Time").ToString(); Is this correct? but still i have same time change only.. – PoliDev Sep 14 '13 at 08:15
  • No, that's not correct. Please review my updated answer. – Matt Johnson-Pint Sep 14 '13 at 15:35