Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I parse the following time in C# ?
15:31:58:13943730921
What are the last 11 digits?
Something naive would be:
var time = "15:31:58:13943730921";
var str = time.Split(':');
var res = new TimeSpan(int.Parse(str[0]), int.Parse(str[1]), int.Parse(str[2])).Add(TimeSpan.FromTicks((long.Parse(str[3]) + 5000) / 10000));
Note that it won't work if the number of digits of the fractions of seconds change.
Ah... and it's a TimeSpan, not a DateTime probably :-)
The + 5000) / 10000 is to round to the nearest Tick.
A more complete solution that will handle any number of digits:
var time = "15:31:58:13943730921";
var str = time.Split(':');
// Used for the rounding
int carryover = 0;
if (str[3].Length < 7)
{
str[3] = str[3] + new string('0', 7 - str[3].Length);
}
else if (str[3].Length > 7)
{
char eight = str[3][7];
if (eight >= 5)
{
carryover = 1;
}
str[3] = str[3].Remove(7);
}
var res = new TimeSpan(int.Parse(str[0]), int.Parse(str[1]), int.Parse(str[2])).Add(TimeSpan.FromTicks(long.Parse(str[3]) + carryover));
Note that the TimeSpan constructor doesn't support a hour/minute/seconds + ticks, so we have to handle it in a different way (by using the .Add). Other solutions are clearly possible.
This is what I have done.
internal string GetTime(string line)
{
// ...
string tmp = time.Substring(0, 12);
time = DateTime.ParseExact(tmp, "HH:mm:ss:fff", CultureInfo.CurrentUICulture).Ticks.ToString();
return time;
}
If you want to round correctly to a whole number and ticks, with .NET 4.0 and later you can do:
string time = "15:31:58:13943730921";
var ts = TimeSpan.ParseExact(time.Remove(16), "h':'mm':'ss':'fffffff", null);
if (time[16] >= '5')
ts += new TimeSpan(1L); // add one tick for better rounding
Console.WriteLine(ts);
16 is the index in the string of the first character that we have to throw away.
May seem like an obvious answer.. But the question isn't too clear.
DataTime time = DateTime.Now;
string myTime = time.ToShortTimeString();
myTime = myTime.SubString(0, 7);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Let's say you have two numbers, 4 and 9. The numbers can't be less than 0 or more than 9.
I want to fill the gap between 4 and 9 with numbers in correct order like so:
456789
How does one exactly do so? I've been stuck on this problem for the past 2 hours.
Thank you.
I have tried putting the numbers into an array and using the array's length as a way to fill in the numbers.
I've tried numerous other things that I don't know how to explain.
Just create a loop and loop thru all the integers between your numbers and add each number to a string if that is your desired output:
string CreateNumberSequence(int start, int end){
var sb = new StringBuilder();
for(int i = start; i <= end; i++){
sb.Add(i.ToString());
}
return sb.ToString();
}
Note that 10-12 would produce 101112, so you might want to add some separator between numbers, or just create a list of numbers and do the formatting separatly. You could also use Enumerable.Range, but if you are new to programming it is useful to know how to use plain loops.
If you want a list of numbers, change StringBuilder to List<int>, remove all the .ToString() and change the return-type. Or just use the previously mentioned Enumerable.Range.
You can use Enumerable.Range
int start = 4, end = 10;
int[] range = Enumerable.Range(start, end - start + 1).ToArray();
// range: 4 5 6 7 8 9 10
You can use the range method. since you know the start and end of the sequence you can put the start as 4 and the difference to the end from counting all the way from start will be 6.
and for 10-12 it will be like
var number = Enumerable.Range(10, 3);
var number = Enumerable.Range(4, 6);
var result = string.Join("", number.Select(x => x.ToString()).ToArray());
With extension methods :
public static class Ext
{
public static bool ToIntValue(this IEnumerable<int> source, out int output)
{
string joinedSource = string.Join(string.Empty, source);
return int.TryParse(joinedSource, out output);
}
public static IEnumerable<int> NumbersBetween(this int start, int end)
{
if (start > 0 && end <= 9 && start <= end)
{
for (int i = start; i <= end; i++)
yield return i;
}
else
{
throw new ArgumentException("Start and end must be beetween 1 and 9 and end must be bigger than start.");
}
}
}
use case :
if (1.NumbersBetween(9).ToIntValue(out int result))
{
Console.WriteLine(result);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hello I am quite new to C# and I am facing difficulty in adding time as an int . For example,
01:30 Hr
09:45 Hr
13:27 Hr
are hours. I want to convert these to minutes.
How do I add these as int so that I get:
90 + 585 + 825
Is there a way to perform this operation in C#?
public int total_time;
void Start()
{
total_time = time_1 + time_2 + time_3;
}
Let's suppose that your time data are stored in this way:
var dataSource = new List<string>
{
"01:30 Hr",
"09:45 Hr",
"13:27 Hr"
};
Then all you need to do is to
get ride of the Hr suffix
convert them to TimeSpan
sum their TotalMinutes
var total = dataSource
.Select(data => data.Substring(0, 5))
.Select(time => TimeSpan.Parse(time).TotalMinutes)
.Sum();
Obviously this is a naive implementation and really fragile.
A more robust solution would use
regex to get the time portion of the string
use TimeSpan's TryParse to avoid runtime exceptions in case of mailformed inputs.
UPDATE
Based on the comment of Drag and Drop, here is an alternative which could give you better precision:
var total = dataSource
.Select(data => data.Substring(0, 5))
.Select(time => TimeSpan.Parse(time))
.Aggregate(TimeSpan.Zero, (t1, t2) => t1 + t2)
.TotalMinutes;
This approach could be used as well whenever you introduce seconds as well.
(You just need to adjust the Substring parameters.)
Why don't you use TimeSpan struct? TimeSpan struct does exactly what you want.
TimeSpan thirtyMinute = new TimeSpan(0, 30, 0); // Hours, Minutes, Seconds
TimeSpan s = new TimeSpan(1, 24, 60, 60, 100); // Day, Hours, Minutes, Seconds, Miliseconds
TimeSpan oneHour = thirtyMinute + thirtyMinute; // You can add TimeSpan to another == 1 Hour
Here is how to convert hour string
Debug.Log(string.Format("You were out of game for: {0} minutes and {1:00} seconds", (int)totalExitTime / 60, (int)totalExitTime % 60));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Im looking for a way to combine my integers together.
I got 3 integers i want to make one from them.
All the integers are holding a time currency wich looks a little like this:
var date = DateTime.Now;
int timeHours = date.Hour;
I got the Hours, Minutes and Seconds and want to combine so they would look like this:
Hour : Minutes : Seconds
How can i combine the integers together to do that.
Note: I've looked on the internet but i could not get the information i was looking for.
This is what i looked at:
Combine two integers to create a unique number
How to combine 2 integers in order to get 1?
Combining these integers will generate a string, not an another integer. You can easily format your DateTime with ToString() method like;
var str = DateTime.Now.ToString("H':'m':'s"); // eg: 11:0:2
If you wanna get your hour, minute and second part with leading zeros for single digits, you can use HH:mm:ss format instead.
var str = DateTime.Now.ToString("HH':'mm':'ss"); // eg: 11:00:02
DateTime.Now already contains all information you need, date and time. All you need to do is format this information
There're many ways to pack two (or many) integers into one based
on their ranges, e.g.
int i1 = 123;
int i2 = 456;
// two 32-bit integers into 64-bit one
long result = (((long) i1) << 32) | i2;
In your particular case
int hours = 5;
int minutes = 10;
int seconds = 59;
int combined = hours * 3600 + minutes * 60 + seconds;
reverse:
int combined = 12345;
int seconds = combined % 60;
int minutes = (combined / 60) % 60;
int hours = combined / 3600;
you can try the below code i think it's useful
var date = DateTime.Now;
var result = date.Hour + ":" + date.Minute + ":" + date.Second;
Console.WriteLine(result);
A simple way using the base 10 number system is to just
var number = hours * 10000 + minutes * 100 + seconds
this returns a number like 150936 for 15:09:36
To convert back:
seconds = number % 100
minutes = (number / 100) % 100
hours = number / 10000
Note that this is obviously not the most efficient approach, but simple
You should cast to string with format function for example:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
Just to be complete:
format HH:mm:ss:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("HH:mm:ss");
format H:m:s:
string result = string.Format("{0}:{1}:{2}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("H:m:s");
I have a DateConverter class that does all the basics. However, I want to add another type to it. I want to be able to have a 'Descriptive' type that returns the difference between the date and DateTime.Now formatted as a string.
IE: "seconds ago", "7 minutes ago", "8 hours ago"
Whichever the larger increment is.
I suppose the only thing I am missing is figuring out how to get the difference between the two dates in seconds. C# is still a little new to me.
you can subtract two datetime objects and it will return TimeSpan
and you can get Seconds property of TimeSpan
var timespan = (datetime1 - datetime2);
var seconds = timespan.Seconds;
var Minutes = timespan.Minutes;
var hours = timespan.Hours;
I suppose the only thing I am missing is figuring out how to get the
difference between the two dates in seconds.
then you want timespan.TotalSeconds
what about using an extension method instead, like
public static string FromNowFormatted(this DateTime date)
{
var sb = new StringBuilder();
var t = DateTime.Now - date;
var dic = new Dictionary<string, int>
{
{"years", (int)(t.Days / 365)},
{"months", (int)(t.Days / 12)},
{"days", t.Days},
{"hours", t.Hours},
{"minutes", t.Minutes},
{"seconds", t.Seconds},
};
bool b = false;
foreach (var e in dic)
{
if (e.Value > 0 || b)
{
var v = e.Value;
var k = v == 1 ? e.Key.TrimEnd('s') : e.Key ;
sb.Append(v + " " + k + "\n");
b = true;
}
}
return sb.ToString();
}
demo
Note: there are some things with this code you'll need to fix-up such as the ways years and months are calculated.
Edit: you could use Noda Time's Period.Between() which calculates the difference and then just have an extension method as above, that would simply format it in a similar way. see the secion "Finding a period between two values" here for more info.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have this code and its working but i want it to return dailyTotals list with four values, at the moment it is being returned with three values ... i cant seem to figure out how to make it return dailyTotals with four values. BTW the billTotals and dateList are of the same lengh which is currently 7 and they will grow. billTotals and dateList will always remain the same length
List<double> dailyTotals = new List<double>();
string dateValue = "";
double oneDayTotal = 0;
int n = 0;
for (int i = 0; i < billTotals.Count; i += n)
{
dateValue = dateList[i];
oneDayTotal = 0;
while (dateValue == dateList[n])
{
oneDayTotal += billTotals[n];
n++;
}
dailyTotals.Add(oneDayTotal);
}
return dailyTotals;
[EDIT]: Im sorry i should have written this before :/
in the database i have billTotals and the date for each bill stored. so, one date can have multiple bills associated with it. what im trying to do is grab one months data and sum the totals for each day. so the logic i used in the while loop is supposed to sum up the totals while the date is the same ... i hope this makes the scenario more clear. :)
You never reset n, so you are increasing i by increasingly large amount, skipping over some numbers.
You need to set n = 0 inside the loop.
int n = 0;
for (int i = 0; i < billTotals.Count; i += n)
{
dateValue = dateList[i];
oneDayTotal = 0;
n = 0; // This counts the number of equal dates.
while (i + n < dateList.Length && dateValue == dateList[i + n])
{
oneDayTotal += billTotals[i + n];
n++;
}
dailyTotals.Add(oneDayTotal);
}
return dailyTotals;
You could also rewrite the code entirely to simplify it and avoid this curious way of incrementing your loop variable. I would suggest creating an array of objects that hold both the date and the total, then you can use LINQ to solve your problem without any complex loops:
var dailyTotals = datesAndTotals
.GroupBy(x => x.Date)
.Select(g => g.Sum(x => x.BillTotal))
.ToList();
You can also use Zip instead of creating a separate class, though it will be more readable with the class.