How to set current time to a value - c#

I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;

As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.

try DateTime class
DateTime dt = DateTime.Now;

Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;

Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8

A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)

Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.

You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.

Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.

If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;

Related

Easily calculate the time before midnight in C#

I have a function which is already compact, i wanted to know if there was better (like a DateTime functionality already included).
Currently i use this:
DateTime today = DateTime.Now;
DateTime tomorrow = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0).AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
Thank for reading.
You can simplify the tomorrow value by just doing this and taking the benefit of DateTime.Today:
DateTime tomorrow = DateTime.Today.AddDays(1);
So your code will be easy to read:
DateTime today = DateTime.Now;
DateTime tomorrow = DateTime.Today.AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
You can create extension for DateTime
public static class DateExtensions
{
public static double GetNextDayRemainingMs(this DateTime dateTime)
{
return (dateTime.AddDays(1).Date - dateTime).TotalMilliseconds;
}
}
Usage
DateTime.Now.GetNextDayRemainingMs();
You can try following code
(DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds
Instead of defining instance for tomorrow variable you can use .AddDate(1).Date property
.AddDate(1) will add one day to DateTime.Now and .Date property
will give you only date and sets time to 00.
DateTime today = DateTime.Now;
double remaining = (today.AddDate(1).Date - today).TotalMilliseconds;
Or (Elegant way)
You can use Today property of DateTime.
An object that is set to today's date, with the time component set to
00:00:00.
double remaining = (DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds

Alternative Datetime.Now with only time (21:10)

I was wondering if there's a method or anything which will provide me the current systemtime without the date. I need to use this in a formula and if i want to use the DateTime.NowI have to String.Split this string before I can convert this to a Int.
example: It's 5pm
I want:
'17:00', '5:00', '1700', '500'
Not:
'17:00 PM 29/03/2013'
A DateTime holds the hour and minutes as properties.
var now = DateTime.Now;
var minutes = now.Minute;
var hours = now.Hour;
why cannot you simply format your date i.e.
string CurrentTime = DateTime.Now.ToString("hh:mm:ttt");
I guess what you are looking for is how to format a DateTime correctly.
Look here or here for how this is done.
You could use TimeOfDay. Basically it extracts the time part of a DateTime:
DateTime now = DateTime.Now;
TimeSpan time = now.TimeOfDay;
Do note that unlike the DateTime.Date property, DateTime.TimeOfDay returns a Timespan, not a DateTime.
for "1700" :
date.ToString('HHMM');
Use the DateTime.ToString method:
DateTime dt = DateTime.Now; // Suppose it is currently 5pm
dt.ToString("HH:mm"); // 17:00
dt.ToString("h:mm"); // 5:00
dt.ToString("HHmm"); // 1700
dt.ToString("hmm"); // 500

DateTime calculation

I have been getting an annoying issues. I have two datetime variables. Date of employment and termination date. I need to get the number of days work. termindation date - date of employment.
how do i go about getting this?
DateTime empDate = int.Parse((employeeEmploy.ElementAt(i).dateofEmpl).GetValueOrDefault().ToString("yyyyMMdd"));
DateTime terminDate = int.Parse((employeeEmploy.ElementAt(i).terminDate ).GetValueOrDefault().ToString("yyyyMMdd"));
int? dWorked = terminDate - empDate;
I tried that but that didnt work
Well, you're trying to deal with DateTime values - so you shouldn't be using int.Parse to start with. Use DateTime.ParseExact. Once you've got two DateTime values, you can use subtraction to get a TimeSpan, and then compute the total days from that:
DateTime employmentDate = ...;
DateTime terminationDate = ...;
TimeSpan employmentDuration = terminationDate - employmentDate;
int days = (int) employmentDuration.TotalDays;
Personally I'd actually use my Noda Time project to do all of this, mind you:
private static LocalDatePattern TextPattern =
LocalDatePattern.CreateWithInvariantInfo("yyyyMMdd");
...
LocalDate employmentDate = TextPattern.Parse(...).Value;
LocalDate terminationDate = TextPattern.Parse(...).Value;
int days = Period.Between(employmentDate, terminationDate, PeriodUnits.Days)
.Days;
Subtracting DateTime objects produces TimeSpan. So, use TimeSpan.TotalDays to get total days count between two dates:
int dWorked = (terminDate - empDate).TotalDays;
UPDATE: For LINQ to Enitites use EntityFunctions.DiffDays method, which calculates days between two nullable dates:
from x in context.Foo
select EntityFunctions.DiffDays(x.FromDate, x.ToDate)
try something along the lines of
var numDays = (terminDate - empDate ).TotalDays;
dworked = (int)Math.Round(numDays, MidpointRounding.AwayFromZero);
You can easily substract the two Datetimes which gets you a TimeSpan!
DateTime employmentDate = new DateTime(2013,03,8);
DateTime terminationDate = new DateTime(2013,03,11);
TimeSpan days = terminationDate - employmentDate;
Console.WriteLine("Days: " + days.TotalDays); //Result: "Days: 3"

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;

ASP.NET: Get milliseconds since 1/1/1970

I have an ASP.NET, VB.NET Date, and I'm trying to get the number of milliseconds since January 1st, 1970. I tried looking for a method in MSDN, but I couldn't find anything. Does anyone know how to do this?
Starting with .NET 4.6, The method ToUnixTimeMilliseconds provides a more accurate solution.
From DateTimeOffset:
DateTimeOffset.Now.ToUnixTimeMilliseconds()
From DateTime:
new DateTimeOffset(dateTime).ToUnixTimeMilliseconds()
Source: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.6#System_DateTimeOffset_ToUnixTimeMilliseconds
You can subtract any two DateTime instances and get TimeSpan and TotalMilliseconds would give you total milliseconds. Sample below.
DateTime dt1970 = new DateTime(1970, 1, 1);
DateTime current = DateTime.Now;//DateTime.UtcNow for unix timestamp
TimeSpan span = current - dt1970;
Console.WriteLine(span.TotalMilliseconds.ToString());
one liner
//DateTime.MinValue is 01/01/01 00:00 so add 1969 years. to get 1/1/1970
DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;
Alternatively, you can use the Ticks property and avoid construction of a temporary object:
long epochTime = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000;
However, this isn't entirely
Reasoning:
DateTime d = new DateTime(1970, 01, 01);
var temp = d.Ticks; // == 621355968000000000
This will provide the UNIX Epoch in milliseconds.
(Respects UTC time instead of your local time)
Split(DateTime.UtcNow.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds(), ".", 2)(0)

Categories

Resources