Subtract time from date using format string - c#

If I have a date and time in a DateTime object, can I remove say 10 minutes, or 24 hours etc from the date and time using a format string?
So if I have 1/1/1990 12:30:00pm and I wanted to remove 1 hour from it, can I use a format string?
edit
i need to store diary entries and the user can select a reminder type. so 1 hour before hand. so then i'd like to store the format string in a db that i can get and apply to a datetime to get the reminder date time

Something like this might do what you need. Not sure what you mean by subtracting an hour using a format string though.
DateTime dt = new DateTime(1990, 1, 1, 12, 30, 0);
string s = dt.Subtract(new TimeSpan(1, 0, 0)).ToString("MM/dd/yyyy hh:mm:ss tt")

Best way is to convert to a DateTime object and then back to the formatted string (if that's what you need):
var time = DateTime.Parse("1/1/1990 12:30:00pm");
time = time.AddMinutes(-10);
string timeString = time.ToString("MM/dd/yyyy hh:mm:ss tt");

You can use this in your query if you have..
DATE_SUB(date,INTERVAL expr unit)
Example:
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 1 HOUR)
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 12 MINUTE)
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 45 SECONDS)

Related

Insert time without the date into my database

I tried to insert into my MS Access database a specific format to see how just the "time" in my database behaves, but when I tried to show what I got the date also, but I want to insert just the time.
I tried to convert the datetime variable to specific format and insert that
DateTime starttime = Convert.ToDateTime(DateTime.Now.ToShortTimeString());
DateTime nstarttime = Convert.ToDateTime(starttime.ToString("HH:mm"));
06/04/2019 22:55:00 that what I got and I want just the time
without the date
Your main issue is, that in .Net the time part of a DateTime is not a DateTime but a TimeSpan:
DateTime dateTime = new DateTime(2019, 6, 4, 22, 55, 0);
TimeSpan timePart = dateTime.TimeOfDay;
In Access (VBA) however, a "time only" value is the time of the date of the VBA Date epoch which is 1899-12-30. Depending on how you insert the time in an Access table, you may have to apply the time part to the epoch to obtain a value like that Access would use:
DateTime dateTime = new DateTime(2019, 6, 4, 22, 55, 0);
TimeSpan timePart = dateTime.TimeOfDay;
DateTime vbaEpoch = new DateTime(1899, 12, 30);
DateTime vbaTime = vbaEpoch.AddTicks(timePart.Ticks);
Of course, when reading back the values, ignore the date part:
TimeSpan timeOfDay = vbaTime.TimeOfDay;
This has been answered so many times, but nevertheless here is the link to one of the discussions Link 1:
Please check also this Link 2 with may useful patterns
This detail is one of the actual examples provided on Link 1:
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock
Hope this helps!
Cheers and happy coding!

How to split string value using c# asp.net

I want to split this 2015-08-11 10:59:41.830 value which is in datetime datatype format and convert it to the following format using c# asp.net.
August 11, 45 minutes ago
The given datetime(i.e-2015-08-11 10:59:41.830) will compare with the current datetime and display like the above format.Please help me to do this.
You will need to parse your date using DateTime.Parse(string s) and once you have that, you take the current date (DateTime.Now) and subtract from it the parsed date.
This should yield a TimeSpan struct. Assuming that both of the dates will refer to the same date, you can then construct your string by taking the pieces you need from the parsed date (Day and Month) and from the time span (Hours, minutes and seconds).
For your specific format you can try ParseExact() "yyyy-MM-dd HH:mm:ss.fff"
static void Main(string[] args)
{
//Given that previous and and now is the same day
DateTime previous = DateTime.ParseExact("2015-08-18 10:59:41.830", "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
double value = now.Subtract(previous).TotalMinutes;
Console.WriteLine(string.Format("{0:MMMM dd}, {1} minutes ago", now, (int)value));
Console.ReadLine();
}
npinti already explained it, here the code part;
string s = "2015-08-18 10:59:41.830";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
var ts = dt - DateTime.Now;
Console.WriteLine("{0}, {1} minutes ago",
dt.ToString("MMMM dd", CultureInfo.InvariantCulture),
ts.Minutes);
}
I run this code 2015-08-18 09:50 in my local time and it's generate August 18, 9 minutes ago as a result.
Remember, Minutes property represents minute component of the TimeSpan object and it's range is from -59 to 59. If you wanna get all minutes based on TimeSpan object value, you can use TotalMinutes property (or even as (int)ts.TotalMinutes).
You need this
var yourString = "2015-08-11 10:59:41.830";
var oldDate = DateTime.ParseExact(yourString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
//The above two steps are only for if you have date in `string` type, but if you have date in `DateTime` format then skip these.
var difference = DateTime.Now - oldDate;
//here old date is parsed from string or your date in `DateTime` format
var result = string.Format("{0:MMMM dd}, {1} minutes ago", oldDate, difference.Minutes);

C# 12 hour time difference with integers

I have 14 textboxes that takes a user’s input of two times in a 24 hour clock format. When the calculate button is clicked the difference between the two times is calculated and returns the time in decimal format to the respective label. Ideally I would like the user to simply enter time as an integer, such as 1253 or 925 and select AM or PM from the drop down box. Say a user enters 1115 as the in time with AM selected then enters 300 as the out time with PM selected (as shown in the example entry below), the calculate button is clicked and 3.75 is returned in the label.
I have this code below and it works but I get errors when there aren’t exactly four characters. First question, how do I fix this so if an integer such as 800 will be read as 8:00 and not error out?
DateTime dt = DateTime.ParseExact(MondayW1InTextBox.Text, "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm");
MondayW1Label.Text = timestring;
Second, once the string is formatted to 12 hour format, how can I get it to take the AM/PM drop down list as an argument for calculating the difference?
Below is the current C# code behind for just the Monday textboxes calculation which is just 24 hour time format, but want to move away from 24 hour time.
protected void CalculateButton_Click(object sender, EventArgs e)
{
TimeSpan TimeIn, TimeOut;
if (!TimeSpan.TryParse(MondayW1InTextBox.Text, out TimeIn)) TimeIn = default(TimeSpan);
if (!TimeSpan.TryParse(MondayW1OutTextBox.Text, out TimeOut)) TimeOut = default(TimeSpan);
MondayW1Label.Text = (TimeOut - TimeIn).TotalHours.ToString("f2");
}
Your first problem is related to the pattern you are using to parse the time: ParseExact will always try to match the exact pattern (in your case, "HHmm") to the string being parsed. That means it expects two digits representing the hours and two digits for the minutes. You can easily make it work if you append a leading zero to your string whenever its size is < 4. You can use the PadLeft method for doing that:
DateTime dt = DateTime.ParseExact(MondayW1InTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
The first argument of PadLeft is the total length of the resulting string (in our case, 4), and the second argument is the character that should be used to fill in ('0').
For your second problem, you can parse the strings to get the DateTime object and, if the PM value is selected, just add 12 hours to the corresponding time.
DateTime timeIn = DateTime.ParseExact(MondayW1InTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
DateTime timeOut = DateTime.ParseExact(MondayW1OutTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
if(dropDownListIn.SelectedValue == "PM") timeIn = timeIn.AddHours(12);
if(dropDownListOut.SelectedValue == "PM") timeOut = timeOut.AddHours(12);
MondayW1Label.Text = (timeOut - timeIn).TotalHours.ToString("f2");
Notice that you can use the subtraction operator on DateTime objects to get the time difference between them, no need to explicitly convert them to TimeSpans.
Maybe this example (it is pretty crude but you get the logic) will be helpful:
string datetime1 = "800";
DateTime dt1 = DateTime.ParseExact((datetime1.Length == 3) ? "0" + datetime1 : datetime1, "hhmm", CultureInfo.InvariantCulture);
string dropDownVal = "AM";
if (dropDownVal == "PM")
dt1 = dt1.AddHours (12);
string datetime2 = "1100";
DateTime dt2 = DateTime.ParseExact((datetime2.Length == 3) ? "0" + datetime2 : datetime2, "hhmm", CultureInfo.InvariantCulture);
dropDownVal = "PM";
if (dropDownVal == "PM")
dt2 = dt2.AddHours (12);
TimeSpan TimeIn, TimeOut;
TimeIn = new TimeSpan (dt1.Ticks);
TimeOut = new TimeSpan(dt2.Ticks);
Console.WriteLine((TimeOut - TimeIn).TotalHours.ToString("f2"));
Console.ReadLine ( );

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.

how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.
Update
Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(
But I still got SO MANY good answers, thanks!
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.
Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.
However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.
Using DateTime:
var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.
Using custom formatting:
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var amPmDesignator = "AM";
if (hours == 0)
hours = 12;
else if (hours == 12)
amPmDesignator = "PM";
else if (hours > 12) {
hours -= 12;
amPmDesignator = "PM";
}
var formattedTime =
String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan represents a time interval not a time of day. The DateTime structure is more likely what you're looking for.
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.
TimeSpan represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
Try This Code:
int timezone = 0;
This string gives 12-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");
This string gives 24-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");
Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:
DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
Yields:
2:00 PM
String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
It is very simple,
Let's suppose we have an object ts of TimesSpan :
TimeSpan ts = new TimeSpan();
and suppose it contains some value like 14:00:00
Now first convert this into a string and then in DateTime
as following:
TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
// value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
// String variable.
DateTime TheTime = new DateTime(); // Creating the object of DateTime;
TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
Console.WriteLine(TheTime.ToString(hh:mm:ss tt));
this will show the Result as: 02:00:00 PM
Normal Datetime can be converted in either 24 or 12 hours format.
For 24 hours format - MM/dd/yyyy HH:mm:ss tt
For 12 hours format - MM/dd/yyyy hh:mm:ss tt
There is a difference of captial and small H.
dateTimeValue.ToString(format, CultureInfo.InvariantCulture);

Categories