i want to calculate a checktime to the time now and get the hours.
I have a string "time" for example...
string t1 = UserParam[12].ToString(); // "9/26"
string t2 = UserParam[13].ToString(); // "14:51\r"
I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.
I want a time how ---> 1 hour(s), 49 minute(s)
I assume t1 is the month and date and t2 is the hour and minute.
You can use DateTime.ParseExact:
string t1 = "9/26";
string t2 = "14:51";
DateTime dt = DateTime.ParseExact(string.Format("{0} {1}", t1, t2), "M/dd HH:mm", CultureInfo.InvariantCulture);
TimeSpan diff = DateTime.Now - dt;
double totalHours = diff.TotalHours; // 0.726172292194444
Edit:
I get a error --> not the right format
Maybe because you have unwanted characters at the end of the string(s) as in "14:51\r". You can use Trim or TrimEnd to remove them. For example:
string t2 = UserParam[13].ToString().TrimEnd(new []{ '\r', '\n' }); // 14:51
You'll want your times in DateTime structures. If you have timestamp information in a string, then you should use DateTime.TryParse to fill a DateTime. But if you have the timestamp in a string it will be important to specify time zone info in the style parameter (DateTimeStyles).
Then you can take make a TimeSpan by subtracting two DateTime stucts and use the TotalHours property
(dt1 - dt2).TotalHours
You can use DateTime.Subtract to calculate the difference between dates and times:
string date = "9/26 14:51";
DateTime dt = DateTime.ParseExact(date, "M/dd HH:mm", CultureInfo.InvariantCulture);
TimeSpan diff = DateTime.Now.Subtract(dt);
Related
Using ASP.NET Forms, I'm encountering a problem with converting a 12 hour time into a timespan. Below I'm combining DateTime with TimeSpan as the user chooses a date and then a time. The fields are controlled by javascript.
DateTime DateResult = DateTime.TryParse(txtDate.Text, out DateResult) ? DateResult : DateTime.Today;
TimeSpan TimeResult = TimeSpan.TryParseExact(txtTime.Text, "h:mm tt", CultureInfo.InvariantCulture, out TimeResult) ? TimeResult : new TimeSpan();
DateResult = DateResult.Add(TimeResult)
So parsing the date works fine, but Timespan doesn't. One example:
Date Entered: 08/03/2018
Time Entered: 3:00 AM
Values are gettined passed okay but time fails so DateResult becomes "08/03/2018 00:00" but not "08/03/2018 03:00". I have also tried using the method TimeSpan.TryParse but no luck with that one.
I've also made sure that the format is correct by manually entering the time in the database behind the scenes. The gridview has a column that shows the full date in this format "dd/MM/yyyy h:mm tt", and works.
Anyone please share some light? Ideally, I would like to avoid any third party plug-ins.
Parse them together
Simplest thing is to just concatenate the strings before parsing as a single DateTime, e.g.
var dateEntered = #"08/03/2018";
var timeEntered = #"3:00 am";
DateTime result;
var completeDateString = dateEntered + " " + timeEntered;
var ok = DateTime.TryParse(completeDateString, out result);
if (!ok) result = DateTime.Today;
Console.WriteLine(result);
Output:
8/3/2018 3:00:00 AM
Ta da
If you have to parse them separately
If you'd like to work with the fields separately, you still can (I guess you'd have to do this if you want the time format to be exact but the date portion to be flexible, as it is in your example). But TimeSpan.TryParseExact is really different from DateTime.Parse. The format codes are different; it doesn't support the ":" character (except as a literal with an escape, e.g. "\:"), for example, or the "tt" formatting specifier. I'm guessing the concept of am/pm has to do with an absolute point in time, not a relative time offset, so isn't provided for. But you can still parse the textbox as a DateTime and use its time portion.
You can probably shorten this a bit but this example gives you everything you need:
static public DateTime ParseDateTime(string input)
{
DateTime output;
var ok = DateTime.TryParse(input, out output);
if (ok) return output;
return DateTime.Today;
}
static public TimeSpan ParseTime(string input)
{
DateTime output;
var ok = DateTime.TryParseExact(input, #"h:mm tt", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out output);
return output.Subtract(output.Date);
}
public static void Main()
{
var dateEntered = #"08/03/2018";
var timeEntered = #"3:00 am";
DateTime dateResult = ParseDateTime(dateEntered);
TimeSpan timeResult = ParseTime(timeEntered);
DateTime finalResult = dateResult.Add(timeResult);
Console.WriteLine(finalResult);
}
Output:
8/3/2018 3:00:00 AM
Code on DotNetFiddle
See ParseExact or https://msdn.microsoft.com/en-us/library/system.timespan.tryparseexact(v=vs.110).aspx for TryParseExact should work for both DateTime as well as TimeSpan inter alia
Fyi it's called the meridian and see also AM/PM to TimeSpan
How may I get the "DateTime" function on a program and convert it into a double variable? My goal is to do some time operations like
(imagine that this variable t1 is a static "time" already written in a label)
(now imagine that t2 is the DateTime from the computer)
t1 = 03:40:11
t2 = DateTime
t3 = t2 (that would be DateTime converted) + t1
How would I turn this DateTime into double so I can do this operation?
You don't need to convert it into a double. You can perform arithmetic directly on the DateTime object:
var date = new DateTime(1944, 6, 6, 1, 10, 0);
var time = TimeSpan.Parse("03:40:11");
var newDate = date.Add(time);
Console.WriteLine(newDate); // Prints "06/06/1944 04:50:11"
Multiple operations are possible on raw TimeSpans. However, you can use it's TotalSeconds, TotalHours etc. propetries, which are double. Later, you can return to the TimeSpan world by TimeSpan.FromMinutes(m1 + m2 * 7.5).
There is no operator for adding two DateTime's. And since a DateTime is an absolute time value it would make much sense to add two absolute time values.
But you can do:
DateTime dt = DateTime.Now;
TimeSpan ts = TimeSpan.Parse("12:00:00");
DateTime dt1 = dt + ts; // Adding a TimeSpan to a DateTime
TimeSpan ts1 = DateTime.Now - dt; // Substracting two DateTimes
I've done like RB and it worked, btw I've found what was missing for my program to do this kind of addition.
I forgot to call a variable "DateTime" that would be "DateTime.Now" and I finished it doing:
dateTime = my variable which gets the time from the computer
timeSpan - my variable which has a static time number
var finalTime = dateTime.Add(timeSpan).
Thank you guys for your help!
Is there any way I don't have to specify the number of digits in day/month/year?
For e.g 1/2/1991
I want a method which satisfies both 1/2/1991,11/3/1990,12/12/1991
I don't know how many digits will be there in either month, year, or days.
My code is
string copy = splittedData[0] + splittedData[1] + splittedData[2];//date+month+year
DateTime datetime = DateTime.ParseExact(copy, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime dateAndTime = datetime;
The problem is the number of digits in splitted data array are not known to me and thus the above format "ddMMyyyy" give me exception on some cases.
Since you already have the day month and year then just create a date with the three of them like so;
DateTime date = new DateTime(year, month, day);
No parsing is necessary. You already have all the fields you want to create the date, and you dont need to put it into a special format to create a date.
If you are not sure the if the input is valid, then wrap the creation in a try/catch block to catch an ArgumentOutOfRangeException should it should occur.
Since you updated your question with the code you have, you can concatenate date components with a separator like:
string copy = splittedData[0] + "/" + splittedData[1] + "/" + splittedData[2];
Later you can do:
DateTime dt = DateTime.ParseExact(copy, "d/M/yyyy", CultureInfo.InvariantCulture);
I used the format "d/M/yyyy" with single d and M which would account for both single/double digit day/month.
So it will work for dates like:
01/01/2013
1/01/2013
22/09/2013
02/9/2013
DateTime.ParseExact is specifically intended to not allow what you are asking for. DateTime.Parse will allow it, though.
You say you have the 3 parts as separate strings -- if you insert the /'s and parse, it should succeed (InvariantCulture expects the order month-day-year):
string datetimeString = string.Join("/", new[] {month, day, year});
DateTime datetime = DateTime.Parse(datetimeString, CultureInfo.InvariantCulture);
Or you could convert them to integers and construct a DateTime directly:
DateTime datetime = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
What #n00b said. You've already got the individual components of the date: why are you globbing them back together just so you can call DateTime parsing routines? Just do something like this:
private static DateTime StringToDateTime( string year , string month , string day )
{
int yyyy = int.Parse(year) ;
int mm = int.Parse(month) ;
int dd = int.Parse(day) ;
DateTime dt = new DateTime(yyyy,mm,dd) ;
return dt ;
}
As an added bonus, The above code will probably run faster than DateTime.Parse() or DateTime.ParseExact().
I m trying to get date count from month calender on C# .my code like this
leave.Amount = Convert.ToInt32((mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays.ToString());
I got error like this
Input string was not in a correct format.
TimeSpan.TotalDays property is of type double, you can get the integer part like:
leave.Amount = (int) (mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays;
Consider the following example:
double d = 123.22d;
int number = Convert.ToInt32(d.ToString());
The would result into the exception
Input string was not in a correct format.
So in your code, you can leave out the call ToString and it would be fine, like:
leave.Amount =
Convert.ToInt32(
(mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays);
Here’s a step by step example on how to diff two datetime objects. Just apply this to your code
DateTime startDate = DateTime.Parse("01/01/2013");
DateTime endDate = DateTime.Parse("05/22/2013");
TimeSpan dateDiff = endDate.Subtract(startDate);
int dayDiff = dateDiff.Days;
If you want to round fractional days (like 4 days 18 hrs) days to the nearest one (5 in this case) then use TotalDays property and convert to Int.
This is the way i did for datetimepicker hope it will work to monthcalender
DateTime dt;
DateTime Todate ,FromDate;
Todate = DateTime.ParseExact(datetimepicker1.Value.Date.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
FromDate = DateTime.ParseExact(datetimepicker2.Value.Date.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
double datedifference = (Todate - FromDate).TotalDays;
Then can check as date checking like this
if(datedifference <2)
{
something ..........
}
I have a value stored in variable of type System.TimeSpan as follows.
System.TimeSpan storedTime = 03:00:00;
Can I re-store it in another variable of type String as follows?
String displayValue = "03:00 AM";
And if storedTime variable has the value of
storedTime = 16:00:00;
then it should be converted to:
String displayValue = "04:00 PM";
You can do this by adding your timespan to the date.
TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt"); // It will give "03:00 AM"
Very simple by using the string format
on .ToSTring("") :
if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.
if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.
if you add "tt" ->> The Am/Pm designator.
exemple converting from 23:12 to 11:12 Pm :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt"); // this show 11:12 Pm
var res2 = d.ToString("HH:mm"); // this show 23:12
Console.WriteLine(res);
Console.WriteLine(res2);
Console.Read();
wait a second, there is a catch, the system Culture !!, the same code executed on windows set to different language
especially with different culture language will generate different result.
for example in windows set to Arabic language the result Will be like this :
// 23:12 م
م means Evening (first letter of مساء) .
in windows set to German language i think it will show // 23:12 du.
you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it, do a rebuild (execute) of your app and watch what i'm talking about.
so how can you force showing Am and Pm prefix in English event if the culture of the current system isn't set to English ?
easy just by adding two lines ->
the first step add using System.Globalization; on top of your code
and modify the previous code to be like this :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show 11:12 Pm
InvariantCulture => using default English Format.
another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?
Solution for Arabic Exemple :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE"));
this will show // 23:12 م
event if my system is set to English region format.
you can change "ar-AE" if you want to another language format. there is a list for each language.
exemples :
ar ar-SA Arabic
ar-BH ar-BH Arabic (Bahrain)
ar-DZ ar-DZ Arabic (Algeria)
ar-EG ar-EG Arabic (Egypt)
.....
You can add the TimeSpan to a DateTime, for example:
TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");
Demo: http://ideone.com/veJ6tT
04:00 PM
Standard Date and Time Format Strings
Doing some piggybacking off existing answers here:
public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
return new DateTime().Add(timeSpan).ToShortTimeString();
}
public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}
string displayValue="03:00 AM";
This is a point in time , not a duration (TimeSpan).
So something is wrong with your basic design or assumptions.
If you do want to use it, you'll have to convert it to a DateTime (point in time) first. You can format a DateTime without the date part, that would be your desired string.
TimeSpan t1 = ...;
DateTime d1 = DateTime.Today + t1; // any date will do
string result = d1.ToString("hh:mm:ss tt");
storeTime variable can have value like
storeTime=16:00:00;
No, it can have a value of 4 o'clock but the representation is binary, a TimeSpan cannot record the difference between 16:00 and 4 pm.
You will need to get a DateTime object from your TimeSpan and then you can format it easily.
One possible solution is adding the timespan to any date with zero time value.
var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");
The output value will be "03:00 AM" (for english locale).
You cannot add AM / PM to a TimeSpan. You'll anyway have to associate the TimaSpan value with DateTime if you want to display the time in 12-hour clock format.
TimeSpan is not intended to use with a 12-hour clock format, because we are talking about a time interval here.
As it says in the documentation;
A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.
Also Microsoft Docs describes as follows;
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.
So in this case, you can display using AM/PM as follows.
TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
Side note :
Also should note that the TimeOfDay property of DateTime is a TimeSpan, where it represents
a time interval that represents the fraction of the day that has elapsed since midnight.
To avoid timespan format limitations, convert to datetime.
Simplest expression would be:
// Where value is a TimeSpan...
(new DateTime() + value).ToString("hh:mm tt");
Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.
TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");
str will be:
str = "04:00 PM"
You can try this:
string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);
you can remove hh or mm or ss or tt according your need
where
hh is hour in 12 hr formate,
mm is minutes,ss is seconds,and tt is AM/PM.
Parse timespan to DateTime. For Example.
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
public TimeSpan GetTimeSpanValue(string displayValue)
{
DateTime dateTime = DateTime.Now;
if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
else
dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
return dateTime.TimeOfDay;
}
At first, you need to convert time span to DateTime structure:
var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)
Then you need to convert the value to string with Short Time format
var result = dt.ToString("t"); // Convert to string using Short Time format
Because this situation is as annoying as it is common... I created a helper class, which I have released in a NuGet package. This could be a private method and can be used in MVC views as well as in back-end C# code.
public static string AsTimeOfDay(TimeSpan timeSpan, TimeSpanFormat timeSpanFormat = TimeSpanFormat.AmPm)
{
int hours = timeSpan.Hours;
int minutes = timeSpan.Minutes;
string AmOrPm = "AM";
string returnValue = string.Empty;
if (timeSpanFormat == TimeSpanFormat.AmPm)
{
if (hours >= 12)
{
AmOrPm = "PM";
}
if (hours > 12)
{
hours -= 12;
}
TimeSpan timeSpanAmPm = new TimeSpan(hours, minutes, 0);
returnValue = timeSpanAmPm.ToString(#"h\:mm") + " " + AmOrPm;
}
else
{
returnValue = timeSpan.ToString(#"h\:mm");
}
return returnValue;
}