Convert Decimal to Hours Minutes and Seconds in C# .Net - c#

I have an minutes field in a database like 138.34 that I need to convert back to HH:MM:SS What is the easiest way to do this?

You can use the TimeSpan.FromMinutes(minutesInDouble), pass the above value in double format.
For more information - check MSDN link here

Use the TimeSpan structure:
var timeSpan = TimeSpan.FromMinutes(138.34);
int hh = timeSpan.Hours;
int mm = timeSpan.Minutes;
int ss = timeSpan.Seconds;
Result:
Console.WriteLine("Hours:{0} Minutes:{1} Seconds:{2}", hh, mm, ss);
// Hours:2 Minutes:18 Seconds:20

Related

How can I remove Milliseconds from the TimeSpan in C#? [duplicate]

This question already has answers here:
How can I String.Format a TimeSpan object with a custom format in .NET?
(20 answers)
Closed 6 years ago.
I am new to c# and using windows forms. the result of this code is: 01:38:07.0093844 . Anyone knows how can I remove the millisecond part (0093844) from the result (ts) I want the result to look like this : 01:38:07 (H:mm:ss) without millisecond .
Please help .Thank you
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;
TimeSpan ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)); //Difference
//result of ts = 01:38:07.0093844
Create an extension method:
public static class TimeExtensions
{
public static TimeSpan StripMilliseconds(this TimeSpan time)
{
return new TimeSpan(time.Days, time.Hours, time.Minutes, time.Seconds);
}
}
Usage:
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;
TimeSpan ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)).StripMilliseconds();
To format (make into a string) without milliseconds use this:
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;
TimeSpan ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime));
string formatted = ts.ToString(#"dd\.hh\:mm\:ss");
You can round through a division and a multiplication by the number of Ticks per second:
ts = new TimeSpan(ts.Ticks / TimeSpan.TicksPerSecond * TimeSpan.TicksPerSecond);
Internally a TimeSpan is "simply" a number of Ticks. By doing an integer division and an integer multiplication you can "round" them.
What the object contains and what you want on the screen are separate concerns, do not mix the 2. If you want it formatted on the screen as hourse, minutes, seconds then use ToString() and include that in your format. Example:
var forScreen = ts.ToString("hh:mm:ss");
See all the formatting options available on MSDN Custom TimeSpan Format Strings.
Edit
As mentioned, you can make it whatever you want. Here is an example of ToString which builds out a human readable string. These formatters are meant to build a string that you can display so you do not have to actually make changes to the underlying data. This is your presentation logic.
dif.ToString("'Elapsed: 'dd' days, 'hh' hours, 'mm' minutes and 'ss' seconds'")
You can just format the time like below:
string NewDateTime = ts.ToString("yyyy-MM-dd hh:mm:ss");

How to convert date to 'ccyymmddhhmmss' format?

How to convert date to 'ccyymmddhhmmss' format in c#?
You might want to try this... I don't know if cc is included, so I solved for the cc.
DateTime time = DateTime.Now;
string format = "yyMMddhhmmss";
Console.WriteLine(((Convert.ToInt32(time.ToString("yyyy")) / 100) + 1).ToString() + time.ToString(format));
For "yyMMddhhmmss".....Try this...And don't forget that capital M is Month and lower case m is minutes.
DateTime dt = Convert.ToDateTime("8 Oct 10 19:00");
Console.WriteLine(dt.ToString("yyMMddhhmmss"));
From what I understand from your question, you want to format a c# date object to the specified format?
The easiest way to do that is by using the date.ToString("yyyyMMddHHmmss") - where date is the Date Object... There are several choices to this - like having 12-hour instead of 24-hour etc. The best option is to read through http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and set what you need.
Hope this helps.
#Chris_techno25: I took the freedom to extend your answer:
If we stick to the question of Narashima, he wants the format ccyymmddhhmmss.
So I've scratched up this extension method:
public static string IncludeCentury(this DateTime sourceDate, bool replace)
{
var source = String.Format("{0}/{1}", sourceDate.Year / 100 + 1, sourceDate);
if(replace)
return Regex.Replace(source, "[^0-9]", "");
else
return source;
}
Usage:
var includingCentury = DateTime.Now.IncludeCentury(true)
var includingCentury = DateTime.Now.IncludeCentury(false)
Output:
21218201491410
21/2/18/2014 9:18:10 AM

Convert TimeSpan from format "hh:mm:ss" to "hh:mm"

I want to show in a TextBox only hour and minutes
var test = dataRow.Field<TimeSpan>("fstart").ToString();
//test ="08:00:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
how to show only hours and minutes "hh.mm"
You need to convert your data to TimeSpan and then use format:"hh\:mm"
string test ="08:00:00";
TimeSpan ts = TimeSpan.Parse(test);
Console.Write(ts.ToString(#"hh\:mm"));
In your case:
var test = dataRow.Field<TimeSpan>("fstart").ToString(#"hh\:mm"));
Remember to escape the colon :
You may see: Custom TimeSpan Format Strings
There is no need to convert from hh.mm.ss to hh.mm. TimeSpan is stored as a number of ticks (1 tick == 100 nanoseconds) and has no inherent format. What you have to do, is to convert the TimeSpan into a human readable string! This involves formatting. If you do not specify a format explicitly, a default format will be used. In this case hh.mm.ss.
string formatted = timespan.ToString(#"hh\.mm");
Note: This overload of ToString exists since .NET 4.0. It does not support date and time placeholder separator symbols! Therefore you must include them as (escaped) string literals.
The usual way of formatting strings seems not to work for some odd reason (tested with .NET 3.5). (It does not make any difference whether you escape the separator symbol or not):
var timespan = TimeSpan.FromSeconds(1234);
string formatted = String.Format(#"{0:hh\.mm}", timespan); // ==> 00:20:34
However, you can construct the string like this
string formatted =
String.Format("{0:00}.{1:00}", Math.Floor(timespan.TotalHours), timespan.Minutes);
or starting with VS2015 / C# 6.0, using string interpolation:
string formatted = $#"{timespan:hh\:mm}";
You can use TimeSpan methods:
ToString("hh':'mm")
// or
ToString(#"hh\:mm")
Also check all available formats here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
var test = dataRow.Field<TimeSpan>("fstart").ToString("hh.mm");
//test ="08:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
I know this is a very old question. If anyone wants to show single-digit hours when your hours are a single digit then you can use
var hoursWithMinutes = TimeSpan.FromHours(hours).ToString(#"h\:mm")
This way, when your hours are double-digit I mean greater than 9 then it will be showing 10:00 something like that.
The previous solutions don't run if hours>24, try this solution if you have time in minutes very big
int minutes = 159000;
TimeSpan t = new TimeSpan(0, minutes, 0);
String HOURS = Math.Round(t.TotalHours, 0).ToString();
if (HOURS.Length==1)
{
HOURS = "0"+HOURS;
}
String MINUTES = t.Minutes.ToString();
if (MINUTES.Length == 1)
{
MINUTES = "0" + MINUTES;
}
String RESULT = HOURS + ":" + MINUTES;
You can achieve this by:
var hhmm = TimeSpan.FromMinutes(minutes).ToString(#"hh\:mm")

How can I convert string to time object for calculation

how do I format output in seconds:milliseconds format?
TimeSpan start = TimeSpan.Parse(pair.Value[3]);
TimeSpan end = TimeSpan.Parse(pair.Value[4]);
Console.WriteLine(TimeSpan.Compare( start,end));
The code here is printing the difference in seconds. how can i fix it using string.format as i dont know the convention for milliseconds?
You need to look at the difference between the two timespans.
TimeSpan start = new TimeSpan(42); // 42 ticks
TimeSpan end = new TimeSpan(420000000);
TimeSpan diff = end.Subtract(start);
string ms = diff.Milliseconds.ToString();
string sec = ((int)diff.TotalSeconds).ToString();
Console.WriteLine(sec + ":" + ms);
How about
Console.WriteLine(end.Subtract(start).TotalMilliseconds)
If it's in seconds, you could just multiply the answer by 1000 and write that out as a string?
Otherwise, take a look at this MSDN article http://msdn.microsoft.com/en-us/library/bb882581.aspx

C# Is it possible to convert DateTime format to integer or float?

I'm having some trouble here.
Did some research on Google but I can't seem to find what I'm looking for.
I'm trying to ask for two inputs (datetimes) in hh:mm format, subtract one for the other then return the result of that value in minutes.
The problem is that I want to return that value as an integer and I can't seem to find the right way to do it.
In C/C++ I wouldn't have this kind of issues...
Anyways, here's a snippet of what I'm talking about.
private int DuraçaoTreino(DateTime dtInicioTreino, DateTime dtFimTreino, int dtDuraçao)
{
Console.WriteLine("Introduza a hora de inicio (hh:mm): ");
dtInicioTreino = Convert.ToDateTime(Console.Read());
Console.WriteLine("Introduza a hora de fim (hh:mm): ");
dtFimTreino = Convert.ToDateTime(Console.Read());
dtDuraçao = (dtFimTreino - dtInicioTreino); // duração da sessão de treino
dtDuraçao = Convert.ToDecimal(Console.Read());
return dtDuraçao;
}
And that's pretty much it... I'm new to C# so if you see anything wrong please be kind.
Thanks in advance.
What you're talking about is a TimeSpan:
DateTime dtBegin = new DateTime(2011,5,1,22,0,0) ; // 10pm 1 May 2011
DateTime dtEnd = new DateTime(2011,5,1,23,0,0) ; // 11pm 1 May 2011
TimeSpan tmElapsed = dtEnd - dtBegin ; // tmElapsed is a TimeSpan with a value of 60 minutes
To return the minutes, do something like:
int elapsedTimeInMinutes = (int) Math.Round( tmElapsed.TotalMinutes , 0 ,MidpointRounding.ToEven ) ;
var timeInMinutes = new DateTime(2011, 12, 25).Subtract(new DateTime(2010, 1, 1)).TotalMinutes;
Instead of creating the DateTime objects using the constructor I used, you can use DateTime.Parse, or better still DateTime.ParseExact to convert the strings to date times. (I know I am only using date parts here but you choose only to use time parts if you wish)
Convert DateTime objects to TimeSpan's, substract and call TimeSpan.TotalMinutes (or smth like that - dont' have VS at hand):
DateTime dt1, dt2;
// Assign some dates, then:
TimeSpan ts = dt2 - dt1;
double minutes = ts.TotalMinutes;

Categories

Resources