Save the Datetime in UTC in database - c#

I am facing problem with saving date time in UTC.
I amtaking datetime as input from user after that I want to save that datetime's UTC value in database.
I am using one text box(for taking the exact date) and one dropdownlist(for taking the hours of that date)to get the datetime input values from user.
below is my code to get the exact input datetime from user after combinending both controls value.
like:25/12/2011 as date and 10 hours as hours after combinding both values the date values is 25/12/2011 10:00 AM
fort his calculation I am using below code:
string[] dateArray = HdnDPC_date1.Value.Split('/');
string dtt = dateArray[1] + "/" + dateArray[0] + "/" + dateArray[2];
var fdate = Convert.ToDateTime(dtt);
DateTime dadate = new DateTime(Convert.ToInt32(dateArray[2]), Convert.ToInt32(dateArray[1]), Convert.ToInt32(dateArray[0]));
dadate = Convert.ToDateTime(fdate).AddHours(deadlineHr);
below code is used to convert the date time value in UTC
DateTime DeadLine = TimeZoneInfo.ConvertTimeToUtc(dadate);
but code is not converting the input datetime according to the Time zone, it is always convert according to the "Central Time Zone, USA & Canada"
But I want to convert that datetime according to the user's Timezone.
Please help me to identify this problem why this happened.

You can try using the ToUniversalTime function
DateTime univDateTime = DateTime.Now.ToUniversalTime();
More on ToUniveralTime here

You need to specify the user's timezone. For example:
TimeZoneInfo.ConvertTimeToUtc(dadate,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

Set your thread's current culture to the user's culture like:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage);
See http://msdn.microsoft.com/en-us/library/bz9tc508.aspx

Related

How to convert Server Date time to Indian Standard Time?

I have WebApp deployed on US server. I have used DateTime.Now in order to capture User Date and Time on certain Action by the User.
Localy it works fine and gets the Date time correct. But post the deployment function is saving the date time for the Server Date time and not the User.
Users are in India hence it should capture IST and not MST as what it is doing now.
Here is my Code I have used so far with no success:
//Getting the current UTC Time
DateTime UTCTime = System.DateTime.UtcNow;
//Adding the time difference 5.5 hours to the utc time
DateTime IndianTime = UTCTime.AddHours(5.5);
dto.ChatCreateDateTime = IndianTime;
Using TimeZone Class did not work either.
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime timeUTC = DateTime.UtcNow;
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(timeUTC, timeZone);
dto.ChatCreateDateTime = result;
I did try searching online and tried many fix like TimeZone Class, and other but none worked for me.
Use the below code but no correct datetime. Time shows as behind by 30 mins.
DateTime dateTime = DateTime.Now;
DateTime utcTime = dateTime.ToUniversalTime();
TimeZoneInfo istZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime yourISTTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, istZone);
model.ChatCreateDateTime = yourISTTime;
Chat dto = new Chat();
//dto.CustEmail = model.CustEmail;
dto.CustName = model.CustName;
dto.ChatStartDateTime = model.ChatStartDateTime;
// Gets current local date
// Returns 04/09/12 11:30 in my case
dto.ChatStartDateTime = model.ChatStartDateTime;
Thank you in advance.
If you want to convert time from UTC to any specific Time Zone
you should try follwing way.
DateTime dateTime = DateTime.Now; // I am getting date time here
DateTime utcTime = dateTime.ToUniversalTime(); // From current datetime I am retriving UTC time
TimeZoneInfo istZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); // Now I am Getting `IST` time From `UTC`
DateTime yourISTTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, istZone); // Finally converting it
var hourIST = yourISTTime.Hour; // More granular extraction.
Output:
Note:
I am trying this way and perfectly working for me. If you require
further modification and granularity you could check our official document here.

I want to convert date "2018-05-18 17:16:24.570" to "7/26/2018, 10:42 AM" format in C#

I am retrieving the date as a string from the database and then need to convert it. So that prints in a different format.
I am using
string date = dr[2].ToString();
date = DateTime
.ParseExact(date,"yyyy-MM-dd hh:mm:ss.fff tt ",new CultureInfo.InvariantCulture("enUS"));
But this does not work:
System.FormatException: 'String was not recognized as a valid
DateTime.'
If you work with string you can put ParseExact followed by ToString:
string date = "2018-05-18 17:16:24.570";
// 5/18/2018 05:16 PM
date = DateTime
.ParseExact(date, "yyyy-M-d H:m:s.fff", CultureInfo.InvariantCulture)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
However, it seems you are working with DataReader (dr[2] fragment); if it's your case, Convert is a better option than ParseExact (providing that RDBMS has corresponding Date field):
string date = Convert
.ToDateTime(dr[2])
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
Edit: If you want to change time from UTC to a TimeZone you can try TimeZoneInfo (see all available Time Zones here) e.g.
//TODO: Put the right Time Zone Id here
// Or should it be "Arabian Standard Time"? I've tried to guess
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
string date = TimeZoneInfo
.ConvertTimeFromUtc(Convert
.ToDateTime(dr[2]), zone)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));

String was not recognized as a valid DateTime when string is 13/07/15

I have a string date = 13/07/15 in this format and I want to convert it into DateTime, but I get the error mentioned below
String was not recognized as a valid DateTime.
What can I do to convert into datetime. I have tried this
DateTime dt = Convert.ToDateTime(date);
Never noticed that different cultures write their data and time in different formats? Although the format you use is valid in most Western European countries it is rubbish in the United States.
To overcome this problem, you can ask the system for the current date and time format:
var currentCulture = System.Globalization.CultureInfor.CurrentCulture
IFormatProvider dateTimeFormat = currentCulture.DateTimeFormat;
string dateTxt = #"13/7/2015";
System.DateTime myDate = System.DateTime.Parse(dateTxt, dateTimeFormat);
That should do the trick if your computer has the correct culture.
If you want to be able to understand a lot of cultures, don't ask for the current culture but use one of the constructors of System.Globalization.CultureInfo
Not wise, because does 1/3/2015 mean March 1st, or January 3rd?
Your code DateTime dt = Convert.ToDateTime(date); is perfect. Seems to me like the error is in your database, because it converts it into date if it gets the full year. Please check it in your database.
Do like this,
DateTime date = DateTime.ParseExact(s, "dd/MM/yy", null);
Source : DateTime.ParseExact

Conversion to Time 12 hour Format From String containing Time in 24 hour format

I have a varchar(5) column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration.
For Example
8:18 should be converted into 8:18:00 AM and then should be embedded
with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime
column of DB.
22:20......10:20:00 PM.......8/10/2012 10:20:00 PM
The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012
You can do something like this:
string input = "22:45";
var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);
string timeIn12HourFormatForDisplay = timeFromInput.ToString(
"hh:mm:ss tt",
CultureInfo.InvariantCulture);
var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);
And now the important parts to take in consideration:
The format for parsing uses "H:m" so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;
The format for printing uses "hh:mm:ss tt" because it seems to be the format you desire, however you need to use CultureInfo.InvariantCulture to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;
The full date and time is constructed based on DateTime.Today which returns the today date with a zeroed time and then we just add the time we read from input.
To create the final date and time from another date you can instead use:
var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);
Reference material:
DateTime Structure;
Custom Date and Time Format Strings;
Standard DateTime Format Strings.
create function dbo.COMBINE_DATE_TIME(
#DatePart DateTime, -- DateTime
#TimePart varchar(5)) -- Time
returns DateTime
as begin
return DATEADD(day, DATEDIFF(day,0,#DatePart),
CONVERT(DateTime,ISNULL(#TimePart,''),14))
end
go
string strDate = DateTime.ParseExact("8:18","HHmm",CultureInfo.CurrentCulture).ToString("hh:mm tt");
string fromTime = Convert.ToStr(reader["TimeFrom"]);
string toTime = Convert.ToStr(reader["TimeTo"]);
item.Time=DateTime.Parse(fromTime,CultureInfo.CurrentCulture).ToString("hh:mm tt");
here the property of your model(item.Time here) should be the string.

Get origin time from a datetime string with offset

If I run:
// 7:10 am at a location which has a +2 offset from UTC
string timeString = "2011-06-15T07:10:25.894+02:00";
DateTime time = DateTime.Parse(timeString);
It gives me time = 6/14/2011 10:10:25 PM. This is the local time where I am at (Pacific time i.e. UTC -7).
Is there an elegant way of getting the local time at the origin i.e. 6/15/2011 07:10:25 AM?
You can use TimeZoneInfo:
DateTime localTime = DateTime.Now;
TimeZoneInfo targetTimeZone =
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime targetTime = TimeZoneInfo.ConvertTime(localTime, targetTimeZone);
Actually, the ConvertTimeBySystemTimeZoneId method would be even more succinct:
DateTime targetTime =
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(localTime, "Eastern Standard Time");
You can get information for time zones available using TimeZoneInfo.GetSystemTimeZones().
The DateTimeOffset structure seems to be built to specifically handle timezones. It includes most of the functionality of the DateTime type.
string timeString = "2011-06-15T07:10:25.894+02:00";
DateTimeOffset time = DateTimeOffset.Parse(timeString);
As this article illustrates, you should DateTimeOffset instead of DateTime whenever you need to unambiguously identify a single point in time.
Lock into using TimeZoneInfo - http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx to do conversions. FindSystemTimeZoneById and ConvertTimeFromUtc should be enough. You may need to convert your local DateTime to UTC first with DateTime.ToUniversalTime.
You can format the way DateTime is Parse.
For example, if I want the DateTime to be format in french Canadian format :
IFormatProvider culture = new CultureInfo("fr-CA", true);
DateTime dt = DateTime.ParseExact(dateString, "dd-MM-yyyy", culture);
You can do it the same way for a en-US culture and add the time format to specify the format you want ...

Categories