Convert DateTime from UTC to user location timezone - c#

In db I save DateTime in UTC like this:
CreatedDate = DateTime.UtcNow;
and also for every user I save timezone in this format "+0200", "-0300", "-0430"
now I want to filter results by date
SQL: SELECT * FROM tableName WHERE CreatedDate >= GETDATE()
how add value from timezone column to the selected dateTime?

you can do something similar to this
DateTime utcDateTime = DateTime.UtcNow;
TimeSpan offSet = TimeSpan.Parse("+01:00:00");
DateTime checkDate = utcDateTime + offSet;
and then pass checkDate as parameter to the query

Depending on the language you are using, you can get this from the client application, e.g. for javascript.
var offset = new Date().getTimezoneOffset();
Getting the client's timezone in JavaScript
This way you don't need to store it in the DB.
To add the time back in for your example, use parsing and DATEADD http://msdn.microsoft.com/en-gb/library/ms186819.aspx

Something like this:
storedDate.AddHours(double.Parse(timezoneOffset)/100).ToString();
Untested!
EDIT
Or use something like this: (Again, untested)
TimeZoneInfo[] tz = TimeZoneInfo.GetSystemTimeZones().ToArray();
string t1 = tz.First(t => t.BaseUtcOffset == TimeSpan.FromHours(Math.Round((double.Parse(stored) / 100), 1))).Id;
DateTime time= TimeZoneInfo.ConvertTimeBySystemTimeZoneId(storedDate, t1);

Related

Retrieve a string from database and compare with date

I have a field in database stored as string and i need to convert it back to datetime and then compare if it equals to date. Below is the current implementation I have presently.
var date = DateTime.UtcNow ;
var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Central Africa Standard Time");
DateTime currentTime = TimeZoneInfo.ConvertTimeFromUtc(date, zone);
var loanDate = currentTime.Date.ToString("dd/MM/yyyy").Replace("-", "/");
if (DateTime.ParseExact(firstRepay, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date.ToString("dd/MM/yyyy").Replace("-", "/") == WATTime.Date.ToString("dd/MM/yyyy").Replace("-", "/"))
{ // Do this
}
note that the firstRepay is in the format 06/02/2021 in the database but it might be 06-02/2021 depending on server format.
Assuming loanDate and dbDate are in the same format "dd/MM/yyyy" and the dbDate also can be in "dd-MM/yyyy" format, you can try this code
var dateFromDb="01-02/2021"; // 1 Feb 2021
var loanDate="06/02/2020"; // 6 Feb 2020
var dbDate = dateFromDb.Replace("-", "/");
var dbDateTime = DateTime.ParseExact(dbDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var loanDateTime= DateTime.ParseExact(loanDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var diffDateDays=(dbDateTime-loanDateTime).Days; // = 361
//or you can use it this way:
if ((dbDateTime-loanDateTime).Days > 0) //.... then
If dates are in a different string format you just have to change string
"dd/MM/yyyy" to "MM/dd/yyyy" for example for this date, but the algorithm will be still the same.
Please try to use like below.
string dateString = "21-Jan-2021";
DateTime otherDate=new DateTime(2021,3,3);
// Convert a null string.
DateTime mydateTime;
if(DateTime.TryParse(dateString, out mydateTime))
{
//dateString is converted to DateTime in mydateTime
if(mydateTime==otherDate)//Check with exact Date and time
{
//DB date and other date is equal
}
if(mydateTime.Date==otherDate.Date)//Check with Only date
{
//DB date and other date is equal
}
}
Note: Learn different way to convert string to DateTime How to Convert String To DateTime in C#.
Which database you are using, you should directly parse date in your SQL query.
Below is sample for SQL Server
SELECT CAST('06/02/2021' as date) as MyDate
SELECT CAST(REPLACE('06-02/2021','-','/') as date) as MyDate
SELECT CAST(REPLACE('06-02-2021','-','/') as date) as MyDate
SELECT CAST(REPLACE('06-February-2021','-','/') as date) as MyDate
All these will return date which will be directly casted as DateTime in C#. You can parse all your rows using SQL statement at once.
If you have space or some extra chars that can be managed by trim/ regex.

Retrieve Record from Database based on Local Time

Let's suppose I live in a timezone where Today Date is: 12/3/2014
Before saving record I save the date in UTC, so it would be 12/2/2014
user.Created = DateTime.UtcNow;
Now I have a Search page on which I would like to retrieve record based on the filter "Today". Also I would like to truncate time so I am using DbFunction of EF.
DateTime dateDifference = DateTime.Now.Date;
var result= queryableData
.Where(s => dateDifference ==
DbFunctions.CreateDateTime(s.Created.Year, s.Created.Month,
s.Created.Day, 0, 0, 0)).AsQueryable();
The above query does not return any record because the stored date is in UTC which 12/2/2014, however I am living in a timezone where date is 12/3/2014. So it make sense, how can I modify the above query to meet my requirement. Any suggestion
Now that we know that the value is stored as a DateTime (in UTC), you just need to find the UTC time of midnight at the start of today, and the UTC time of midnight at the end of today.
If you're happy to use the system time zone, you could use:
DateTime today = DateTime.Today;
DateTime startUtc = today.ToUniversalTime();
DateTime endUtc = today.AddDays(1).ToUniversalTime();
var result = queryableDate.Where(s => startUtc <= s.Created &&
s.Created < endUtc);
I don't think you should need DbFunctions for that query. Basically, you don't need a difference at all - you just need to work out what your filter of "today" means in terms of an interval in time, expressed as UTC.
Convert your local date to universal time.
DateTime universalDate = dateDifference.ToUniversalTime();

Merge today's date with a timespan data type value

I'm trying to merge today's date with an existing time value I have stored in a sql server database. Let me give you an example:
ClientTradedTime = "16:52:01" (this is of type timespan)
I want to merge that value with today's date in variable of type DateTime to use it else where, example:
DateTime mydate;
mydate = "2014-02-04 16:52:01" (this is what I want to see when I store it in my database)
How can I solve this problem?
Just Datime.Add() the TimeSpan to the DateTime's Date property and you will get your desired DateTime like:
DateTime updatedDt = mydate.Date.Add(ClientTradedTime);
Consider the following example:
DateTime myDate = DateTime.Now;
TimeSpan ClientTradedTime = new TimeSpan(16, 52, 51);
DateTime updatedDt = myDate.Date.Add(ClientTradedTime);
This will give you:
updatedDt = {04/02/2014 4:52:51 PM}
myDate.Date would give you DateTime with Time set to 00:00:00 and then you can add your TimeSpan to it.

How to get DateTime with a UTC datetime and a particular timezone?

My data in SQL database looks like this:
PubDateUTC PubDateUTCOffset
----------------------- --------------------
2011-08-04 10:02:50.000 +8:00:00
2012-04-23 02:32:25.287 +8:00:00
2010-09-26 04:23:00.000 +8:00:00
What I want is to get a DateTime based on PubDateUTC and PubDateUTCOffset, for example:
2011-08-04 10:02:50.000, +8:00:00 should result in 2011-08-04 18:02:50:000
I have tried with TimeZoneInfo class, but I don't know hot to create a instance of TimeZoneInfo with a string like "+8:00:00", which would be the CreateTimeZoneInfo method below
var tz = CreateTimeZoneInfo(post.PubDateUTCOffset);
return TimeZoneInfo.ConvertTimeFromUtc(post.PubDateUTC, tz);
Is there anyway to do this?
Note: I cannot change the data in SQL database.
You could try something like:
var date = post.PubDateUTC.Add(
TimeSpan.Parse(post.PubDateUTCOffset.Replace("+", ""))
);
The .Replace("+", "") is because TimeSpan will handle -01:00:00 but will choke on +01:00:00
I think you need to use DateTimeOffset class. This thread may be helpful.
http://msdn.microsoft.com/en-us/library/bb546101.aspx
This works, remove any leading "+" from the offset ( "-" are ok)
var d = new DateTimeOffset(DateTime.Parse("2011-08-04 10:02:50.000"),
TimeSpan.Parse("08:00:00"));
d.DateTime - the time in db = 10:02:50
d.LocalDateTime - the time according to your servers timezone
d.UtcDateTime - the time at GMT = 02:02:50
I'm not sure you want 18:02:50 since it is the time at GMT+16 (+16:00:00), unless of course that is how it's encoded in the db, then just ignore this post :)
You should change your post class to have one property:
public DateTimeOffset Published { get; set; }
Then when you read from the database (assuming you have datetime and varchar types in your database):
DateTime utc = DateTime.SpecifyKind(
(DateTime) reader["PubDateUTC"], DateTimeKind.Utc);
TimeSpan offset = TimeSpan.Parse(
((string) reader["PubDateUTCOffset"]).Replace("+", ""))
post.Published = new DateTimeOffset(utc).ToOffset(offset);
Then when you need to consume it, you have all of the options of a full DateTimeOffset:
DateTime local = post.Published.DateTime; // with your offset applied
DateTime utc = post.Published.UtcDateTime; // the original utc value
string s = post.Published.ToString("o"); // 2011-08-04T18:02:50.0000000+08:00

Getting the date only in Convert.ToDateTime() in asp.net

I have a parameter string that passes date value to a stored proc
cmdItemSearch.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#EndDate"].Value = Convert.ToDateTime(DateTime.Now);
The value being passed is "6/30/2010 7:45:00 AM"
I want to pass only "6/30/2010"
How would I do that?
For starters, DateTime.Now is already a DateTime so doesn't need to be converted as you have.
Secondly, you can obtain just the date of Today by using DateTime.Today instead of DateTime.Now.
However, if your date isn't "today" then you can just use yourDateTime.Date to return just the Date.
If you are looking for the mm/dd/yyyy format, you could use
DateTime.Now.ToShortDateString()
That will return the short format, but depends on the current culture
cmdItemSearch.Parameters["#EndDate"].Value = DateTime.Today;
Note that the Today property simply returns a DateTime with the time element set to midnight.
MSDN to the rescue: http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
Create a variable called EndDate
var EndDate = DateTime.Now.ToString("MM/dd/yyyy");
EndDate = Convert.ToDateTime(EndDate);
Now EndDate Type is DateTime;
you pass it as a parameter
cmdItemSearch.Parameters["#EndDate"].Value = EndDate ;

Categories