I am having a date with microseconds, it is calculated by adding ticks from 2000.1.1 basically it works and it looks like:
ulong timestampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = new DateTime(2000, 1, 1, 0, 0, 0);
string dateWithMicroseconds = startDate.AddTicks((long)timestampInTicks).ToString("HH:mm:ss.ffffff");
Problem is with return format, it returns me something like 19:34:34:260100 so miliseconds and microseconds are combined when i try HH:mm:ss.fff:fff I am getting 19:34:34:260:260 so milliseconds are doubled. Is there a way, except for using splitting string, for doing this??
Simplest custom implementation I could think of..
ulong ExtendedTimestamp = 99;
ulong timeStampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = DateTime.Now;
string dateWithMicroseconds = startDate.AddTicks((long)timeStampInTicks).ToString("HH:mm:ss.ffffff");
string dateHHmmss = dateWithMicroseconds.Split('.')[0];
string timeffffff = dateWithMicroseconds.Split('.')[1];
int precision = 3;
string milliSecs = timeffffff.Substring(0, precision);
string microSecs = timeffffff.Substring(precision, timeffffff.Length - precision);
string customFormat = string.Format("{0}:{1}:{2}", dateHHmmss, milliSecs, microSecs);
since the microsecond is millisecond/1000, so as in reference to this date the format will return 01.01.2008 00:30:45.125.125000. Milliseconds: 125, Microseconds:125000
DateTime dates = new DateTime(2000, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with micro and milliseconds: {0:MM/dd/yyy HH:mm:ss.fff.ffffff}",dates);
Related
I have two times like 100:45 and 395:50
I need to find the subtraction and addition between these two times in the asp.net web application
I will expect like this 100:45+395:50=496:35 and 100:45-395:50=295:05
assuming the times are given in a string. then you can split the times to get the equivalent minutes. now it becomes a simple mathematics problem and now perform addition and subtraction accordingly.
string time = "100:45";
string[] parts = time.Split(':');
int hours = int.Parse(parts[0]);
int minutes = int.Parse(parts[1]);
int totalMinutes = hours * 60 + minutes;
so for your case
int mins1 = 100 * 60 + 45;
int mins2 = 395 * 60 + 50;
int totalMinutes = mins1 + mins2;
int totalHours = totalMinutes / 60;
int remainingMinutes = totalMinutes % 60;
string sum = $"{totalHours}:{remainingMinutes}";
use the same concept to get the subtraction as well.
You can convert times to TimeSpan.FromMinutes and to get the desired output using TimeSpan.TotalHours and TimeSpan.Minutes
string s1 = "100:45";
string s2 = "395:50";
TimeSpan spWorkMin = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 +
int.Parse(s2.Split(':')[0]) * 60 +
int.Parse(s1.Split(':')[1]) +
int.Parse(s2.Split(':')[1]));
var sum =string.Format("{0:00}:{1:00}", (int)tSum.TotalHours, tSum.Minutes);//496:35
TimeSpan tsub = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 -
int.Parse(s2.Split(':')[0]) * 60 +
int.Parse(s1.Split(':')[1]) -
int.Parse(s2.Split(':')[1]));
var subtract = string.Format("{0:00}:{1:00}", Math.Abs((int)tsub.TotalHours),Math.Abs(tsub.Minutes)); //295:05
TimeSpan do the trick
TimeSpan ts1 = new TimeSpan(0, 100, 45);
TimeSpan ts2 = new TimeSpan(0, 395, 50);
var tsResult = ts1 + ts2;
string outPut = string.Format("{0}:{1}", Math.Floor(tsResult.TotalMinutes), tsResult.Seconds);
I want to convert the int value 600 to 06:00 and 1700 to 17:00 in C#.
This is what I have tried so far:
int val = 600;
TimeSpan result = TimeSpan.FromHours(val);
string fromTimeString = result.ToString("hh':'mm");
How can this be achieved?
If you have only hours and minutes you can create the TimeSpan like this:
// Assuming val is always valid:
TimeSpan result = new TimeSpan(val / 100, val % 100, 0);
I'm trying to check if a DateTime is greater than another DateTime in a method, but when I try to pass it through the paramaters it says that one of the DateTime is 01/01/0001 even though I didn't pass it through as such.
Method:
int monthsCount2(DateTime date, DateTime birthday, int yOld)
{
int count = 0;
if (birthday.Date >= date.Date)
{
count++;
if (!(yOld == 0))
count += (yOld - 1);
}
else
count += yOld;
return count;
}
Using the method:
Console.WriteLine("You have lived through {0} christmases.",
monthsCount2(christmas, birthDay, (int)yearsOld));
christmas variable:
DateTime christmas = new DateTime(25 / 12 / 2017);
birthDay variable:
try
{
Console.WriteLine("Please enter your Birthdate. (dd/MM/yyyy)");
string input = Console.ReadLine();
birthDay = DateTime.Parse(input);
if (birthDay > DateTime.Now)
throw new FormatException();
}
yearsOld variable:
TimeSpan secondsTimeSpan = DateTime.Now - birthDay;
double secondsOld = Math.Round(secondsTimeSpan.TotalSeconds);
double minutesOld = Math.Round(secondsOld / 60);
double hoursOld = Math.Round(minutesOld / 60);
double daysOld = Math.Round(hoursOld / 24);
double weeksOld = Math.Round(daysOld / 7);
double monthsOld = Math.Round(weeksOld / 4.34524);
double yearsOld = Math.Round(monthsOld / 12, 1);
Input - Console:
Console - Imgur
Locals Debug:
Locals - Imgur
All Code:
Code - Github
The correct syntax to initialize a datetime instance is this:
var christmas = new DateTime(2017, 12, 25);
The constructor is documented here.
And the reason why your approach did not work:
You are dividing 25 by 12, then dividing the result of that by 2017. as an integer, this will be zero, as a date this will be DateTime.MinValue which is 01/01/0001.
So why does the compiler not reject your attempted date literal? Because there is a constructor which takes an Int64 that fits the division expression. It has altogether different semantics though, it represents the
number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar
This is incorrect syntax (or at very least not what you think it is)
DateTime christmas = new DateTime(25 / 12 / 2017);
The numeric values are integers and '/' is divide.
Instead you want to do something like this:
DateTime christmas = new DateTime(2017, 12, 25);
or
DateTime christmas = new DateTime.Parse("12/25/2017");
The format on that last one is culturally dependent.
Suppose i have a DateTime, e. g. 2010.12.27 12:33:58 and i have an interval frames of, suppose, 2 seconds, excluding the last border.
So, i have the following frames:
12:33:58(incl.)-12:34:00(excl.) - let it be interval 1
12:34:00(incl.)-12:34:02(excl.) - let it be interval 2
12:34:02(incl.)-12:34:04(excl.) - let it be interval 3
and so on.
I'm given a random DateTime value and i have to correlate that value according the above rules.
E. g. the value "12:33:58" falls into interval 1, "12:33:59" falls into interval 1, "12:34:00" falls into interval 2 and so on.
In code it should look like the following:
var dt = DateTime.Now;
DateTime intervalStart = apply_the_algorythm(dt);
It seems to be some simple arithmetic action(s) with float or something, any decisions are welcome!
If the interval is only second resolution and always divided 86400, then take the number of seconds that have passed today, divide it by the interval, round it to an integer value, multiply it, and add it back to today. Something like dateinquestion.Subtract(dateinquestion.Date).TotalSeconds, ((int)seconds/interval)*interval, dateinquestion.Date.AddSeconds(...)
If you want the range of all your intervals to span several days, possibly a long time, you might want to express your DateTime values in UNIX-seconds (the number of seconds since 1970-01-01). Then you just find out when your very first interval started, calculate how many seconds passed since then, and divide by two:
int secondsSinceFirstInterval = <currDate in UNIX time>
- <start of first interval in UNIX time>;
int intervalIndex = secondsSinceFirstInterval / 2;
Otherwise you're better off just counting from midnight.
Use TimeSpan.TotalSeconds and divide the result by the size of the interval.
const long intervalSize = 2;
DateTime start = new DateTime(2010, 12, 27, 12, 33, 58);
TimeSpan timeSpan = DateTime.Now - start;
long intervalInSeconds = (long)timeSpan.TotalSeconds;
long intervalNumber = 1 + intervalInSeconds / intervalSize;
DateTime start = new DateTime(2010, 12, 31, 12, 0, 0);
TimeSpan frameLength = new TimeSpan(0, 0, 3);
DateTime testTime = new DateTime(2010, 12, 31, 12, 0, 4);
int frameIndex = 0;
while (testTime >= start)
{
frameIndex++;
start = start.Add(frameLength);
}
Console.WriteLine(frameIndex);
dates = new List<DateTime>
{
DateTime.Now.AddHours(-1),
DateTime.Now.AddHours(-2),
DateTime.Now.AddHours(-3)
};
dates.Sort((x, y) => DateTime.Compare(x.Date, y.Date));
DateTime dateToCheck = DateTime.Now.AddMinutes(-120);
int place = apply_the_algorythm(dateToCheck);
Console.WriteLine(dateToCheck.ToString() + " is in interval :" +(place+1).ToString());
private int apply_the_algorythm(DateTime date)
{
if (dates.Count == 0)
return -1;
for (int i = 0; i < dates.Count; i++)
{
// check if the given date does not fall into any range.
if (date < dates[0] || date > dates[dates.Count - 1])
{
return -1;
}
else
{
if (date >= dates[i]
&& date < dates[i + 1])
return i;
}
}
return dates.Count-1;
}
I want to compare two dateTime.
Ex:
date1 = 13/01/2004 12:20:00
date2 = 13/01/2004 12:35:00
result = Compare(date2-date1);
O/P : 15 Minutes
To compare, you can simply use the < operator: date1 < date2.
If you want to compare with a given resolution, try date1.TotalMinutes == date2.TotalMinutes (this compared for the same minute).
If you want to know if the difference is within a certain time span, use this:
System.TimeSpan dt = date2.Subtract(date1);
if (dt.TotalMinutes < 15) //...
Try this:
TimeSpan diff = date2.Subtract(date1);
How about
if (date1 < date2)
{
// date1 is before date2
}
You can use
double minutes = d2.Subtract(d1).TotalMinutes;
To get the total difference in minutes.
How about:
Timespan ts = date2 - date1;
Console.WriteLine("Value of Minutes = ", ts.Minutes);
I don't fully understand what you're asking.
If you want your pseudo-code expressing in C# here you go...
//date1 = 13/01/2004 12:20:00
DateTime dateTime1 = new DateTime(2004, 01, 13, 12, 20, 0);
//date2 = 13/01/2004 12:35:00
DateTime dateTime2 = new DateTime(2004, 01, 13, 12, 35, 0);
//get the time difference - result = Compare(date2-date1);
TimeSpan result = dateTime2 - dateTime1;
//output is 15
Console.WriteLine(result.TotalMinutes);
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now;
var x = date1.CompareTo(date2);
EDIT: I see now that you wanted to get the time difference between the two dates. For that you use the TimeSpan class.
Now this is the best bet.
using System;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
}
}
// The example displays the following output:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
In the words of Larry Wall there is more than one way to do this. If you are looking for the -1, 0, +1 result of a compare within a certain time interval try one of these variants;
internal static int XDateCompare(DateTime date, DateTime other, int ticks)
{
var diff = date.Ticks - other.Ticks;
var result = Math.Abs(diff) <= ticks ? 0
: diff <= 0 ? -1
: 1;
Console.WriteLine("{0}\t{1}\t{2}\ts={3} milSec={4}", diff, other, result, ticks, date.Subtract(other).Duration().TotalMilliseconds);
return result;
}
internal static int XDateCompare(DateTime date, DateTime other, double milliseconds)
{
double diff =
date.Subtract(other)
.TotalMilliseconds;
var result = Math.Abs(diff) <= milliseconds ? 0
: diff <= 0 ? -1
: 1;
Console.WriteLine("result {0} diff {1} vs ms {2}", result, diff, milliseconds);
return result;
}