save time with the desired date - c#

below is my html code
<MKB:TimeSelector ID="TimeFrom" runat="server" DisplaySeconds="False">
</MKB:TimeSelector>
and a text box which is having a date.
VehicleBookingDate.Text
I want to save date and time in my database. for that if I want to do like below
string t1 = tsTimeFrom.Hour.ToString() + ":" + tsTimeFrom.Minute.ToString() + " " + tsTimeFrom.AmPm.ToString();
DateTime Time_From = Convert.ToDateTime(t1);
It saves time with current date, where as I want to save this time with this date which is in VehicleBookingDate.Text.
how can I do that.

// use a string formatter to pull it all together
string s = string.Format("{0} {1}:{2} {3}",
VehicleBookingDate.Text,
tsTimeFrom.Hour,
tsTimeFrom.Minute,
tsTimeFrom.AmPm);
// You can parse it this way, which will assume the current culture settings
DateTime Time_From = DateTime.Parse(s);
// Or you can be much more specific - which you probably should do.
DateTime Time_From = DateTime.ParseExact(s,
"d/M/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
You may want to use a specific culture instead if you know it.
Be aware that date formats vary significantly by culture. For example, the value 1/4/2013 could be interpreted as either January 4th or April 1st depending on what part of the world you are in. You either need to be culture aware, or you need to explicitly tell your user what format to use.

Related

Convert to DateTime from a string '10-April-2020'

Looking for assistance in converting a date string i receive from a web form, where the format will be something like "10-April-2020". I need to save this into the database in the US date format "yyyy-mm-dd" so that the example date provided would go in as '2020-04-10'.
This is what I have so far, which complains that it is not a valid datetime.
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateExpires = DateTime.ParseExact(LicenseExpiry, "yyyy-MM-dd", culture);
I have also tried the following which also fails.
DateTime dateExpires;
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
if (DateTime.TryParseExact(LicenseExpiry, "yyyy-MM-dd", culture, DateTimeStyles.None, out dateExpires))
{
// Do something
}
Can anyone help with either of the attempts to see what went wrong? I am not allowed to change the Ui/Form to do any client side date manipulation either, and so my solution needs to be done in the C# code behind file.
MM means the month number (from 01 through 12)
To parse 10-April-2020, you
need MMMM, see
Custom date and time format strings
The "MMMM" custom format specifier represents the full name of the month

c# Is it possible to subtract a day in the datetime format

I have the following simple example:
string dt = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss");
I can't change the DateTime.Now, but I can change datetime format yyyy-MM-dd hh.mm.ss. Following this example the result must be today's date, but I need to get yesterday's date with the same parameters except day (year, month, hours, minutes and seconds). E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it possible to use some "-" operator or something else inside the datetime format to achieve the result?
If you want yesterday's date, you can do this
string dt = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh.mm.ss");
DateTime.AddDays() lets you add number of days, positive for future date, negative for past date.
E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it
possible to use some "-" operator or something else inside the
datetime format to achieve the result?
No, it's not possible inside the DateTime format. you can not change any thing. Because it is only for define format of the Date to display in string format. Any addition or subtraction can only be done before converting it to string format as suggested by "Arghya C".
Can you explain your limitation so we can solve your problem.
If you can only influence the date time pattern, than use the roundtrip format and parse the returning string back to a date time, add the calculation and format it into the desired format:
var dateTimeString = badLibrary.GetDateTime("o");
var dateTime = DateTime.Parse(dateTimeString, null, DateTimeStyles.RoundtripKind);
var newDateTime = dateTime.AddDays(-1);
return newDateTime.ToString("yyyy-MM-dd hh.mm.ss");

Convert custom formatted string to DateTime

I am trying to convert a string into a DateTime:
DateTime newDate = new DateTime();
DateTime.TryParse("20150620 800", out newDate);
The default value (1/1/0001 12:00:00 AM) is returned, how can this be correctly converted?
Use ParseExact to take a custom string and convert it,
According to MSDN:
If format is a custom format pattern that does not include date or
time separators (such as "yyyyMMdd HHmm"), use the invariant culture
for the provider parameter and the widest form of each custom format
specifier. For example, if you want to specify hours in the format
pattern, specify the wider form, "HH", instead of the narrower form,
"H".
This conversion is not possible, unless you change your input data.
You would expect this to work: (This really confused me for a bit while writing this)
DateTime newDate = DateTime.ParseExact("20150620 800", "yyyyMMdd Hmm", CultureInfo.InvariantCulture);
But since H must be in its widest form, it must be HH, as it thinks 80 is out of range for the hour measurement. You will need to add a space between 8 and 00, or add a 0 before 8.
These solutions will work:
DateTime newDate = DateTime.ParseExact("20150620 8 00", "yyyyMMdd H mm", CultureInfo.InvariantCulture);
DateTime newDate = DateTime.ParseExact("20150620 0800", "yyyyMMdd HHmm", CultureInfo.InvariantCulture);
If you cannot change this input data (eg, from a database), just perform a substring operation to insert a space between the minutes and hours so .NET can tell which is which:
var text = "20150620 800";
DateTime newDate = DateTime.ParseExact(text.Insert(text.Length - 2, " "), "yyyyMMdd H mm", CultureInfo.InvariantCulture);
DateTime.ParseExact(newDate,"yyyyMMdd Hmm", new DateFormatInfo());
Should work. Double check the .Net date format string reference to make sure it is what you want.

MVC 4 - Force DateTime

Is it possible to force a DateTime object to use a different locale? I wish to populate a DateTime object with a UK DateTime but formatted as US.
I have tried the following:
DateTime ukDateTimeFormat = DateTime.Parse("10/26/2009 06:47", CultureInfo.GetCultureInfo("en-us"));
DateTime usDateTimeFormat = DateTime.Parse("26/10/2009 06:47", CultureInfo.GetCultureInfo("en-gb"));
string strDate = DateTime.Now.ToString(CultureInfo.InvariantCulture);
string[] dateString = strDate.Split('/');
DateTime enterDate = DateTime.Parse(dateString[0] + "/" + dateString[1] + "/" + dateString[2], CultureInfo.GetCultureInfo("en-us"));
Nothing works, I always end up with a UK formatted date.
Any help would be much appreciated :-)
It seems like you're confused between representing a date-time and formatting a date-time.
DateTime does not contain any format, it only represents the actual time. So the question about a US/UK format of a DateTime is meaningless.
If you want to display the time in a different format, that's not a DateTime, that's a string. You can use the various overloads of DateTime.ToString(...) in order to achieve different formatting as a string. There are some built-in formats, and you can specify a locale.
The DateTime object does not have an internal string format as such - your date is stored as a date and formatted on output. You can populate however you wish, however when outputting it, you'll need to specify your format, e.g.:
string formattedDate = ukDateFormat.ToString("MM/dd/yyyy HH:mm");
To format your date for the locale, use this code:
string formattedDate = ukDateFormat.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"))

Save the Datetime in UTC in database

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

Categories