Function to create 24h periods timestamps? c# - c#

I have database where data is stored along timestamp entries, that are keys.
i need a function that can transform a date like DateTime.Now into a timestamp interval representing, for today as example, Aug 30th 00:00:00h to Aug 30th 23:59:59h.
How could i write that function?
What i want is to do something like
select all from table where timestamp is between a and b.(those and b values would represent the initial and terminal timestamps for a day.)
I did not create the db, i cannot modify it, i can only query it.

This will return a tuple representing the interval you probably want:
Tuple<DateTime,DateTime> GetDateInterval(DateTime datetime) {
var start = datetime.Date;
var end = start.AddDays(1).AddTicks(-1);
return new Tuple<DateTime, DateTime>(start, end);
}
Usage:
var interval = GetDateInterval(DateTime.Now);
Console.WriteLine(interval.Item1);
Console.WriteLine(interval.Item2);
Output:
30.08.2011 0:00:00
30.08.2011 23:59:59

Maybe DateTime.Now.TimeOfDay.Ticks is what you are looking for.

Hard to tell what you want, but here is a way to get the interval:
var start = DateTime.Today;
var end = start.AddDays(1).AddSeconds(-1);
It's hard to answer how you should store the values in the DB since you haven't provided enough details about the table layout.

If you have the scope of a day, you can calculate the ticks withing the day:
// ----------------------------------------------------------------------
public long GetTicksOfDay( DateTime moment )
{
return moment.Subtract( moment.Date ).Ticks;
} // GetTicksOfDay

I think what you need is a TimeSpan.
You can just substract one DateTime from another, and the result will be a TimeSpan of the difference.

I guess you might try using a structure as a TimeInterval:
public struct TimeInterval
{
private readonly DateTime _startTime;
private readonly DateTime _endTime;
public DateTime StartTime { get { return _startTime; } }
public DateTime EndTime { get { return _endTime; } }
public TimeInterval(DateTime now)
{
_startTime = now.Date;
_endTime = now.Date.AddDays(1).AddTicks(-1);
}
}
You can call it:
TimeInterval day = new TimeInterval(DateTime.Now);

Related

Compare DateTime against current system time?

I'm trying to make a C# method to fulfill this user story.
These are the 2 acceptance criteria
Start time must be at least one hour later than the current system time.
End time must be at last one hour after start time.
Both of the start and end time must be DateTime values, so I can parse it with the TryParse method.
Here's what I have in my code so far:
`
private DateTime datetime;
public DateTime datetimeStart { get; set; }
public DateTime datetimeEnd { get; set; }
while (true) {
Util.GetInput("Delivery window start (dd/mm/yyyy hh:mm)");
string userInput = ReadLine();
if(DateTime.TryParse(userInput, out datetime))
{
if (datetime.TimeOfDay.Hours - DateTime.Now.TimeOfDay.Hours >= 1) {
datetimeStart = datetime;
}
break;
}
else
{
WriteLine("\tDelivery window start must be at least one hour in the future.");
}
}
while (true) {
Util.GetInput("Delivery window end (dd/mm/yyyy hh:mm)");
string userInput = ReadLine();
if(DateTime.TryParse(userInput, out datetime))
{
if (datetime.TimeOfDay.Hours - datetimeStart.TimeOfDay.Hours >= 1) {
datetimeEnd = datetime;
}
break;
}
else
{
WriteLine("\tDelivery window end must be at least one hour later than the start.");
}
}
`
I'm not fully sure how the DateTime type works yet, but later on, I'd need to get an output string with this format:
"The pickup window for your order will be 04:00 on 30/10/2022 and 20:00 on 30/10/2022", and just replace the data in the string with values from datetimeStart and datetimeEnd
DateTime provides all the tools to write your conditions in straightforward code:
one hour later than / after checkTime
is just
checkTime.AddHours(1)
and
someTime must be at least one hour later than / after checkTime
becomes
someTime >= checkTime.AddHours(1)
So your code may look something like this:
...........................
if (datetime >= DateTime.Now.AddHours(1)) {
datetimeStart = datetime;
}
...........................
if (datetime >= datetimeStart.AddHours(1)) {
datetimeEnd = datetime;
}
...........................
A general rule of thumb is that any internal time keeping should be done in UTC, but when presenting in a UI (form or console) that you may show in local time.
Another rule is that when comparing DateTime objects that they should have the same Kind.
Perhaps add something like:
DateTime earliestStartTime = DateTime.UtcNow.AddHours(1);
Later if you have a variable named startTime you want to make sure that it is greater than or equal to earliestStartTime. Once you have startTime set, you can then have:
DateTime earliestEndTime = startTime.AddHours(1);
and likewise compare endTime to earliestStartTime for validity.
When presenting times to the user, you can use the .ToLocalTime() method.

Change the date part of a DateTime property before database record created

I have a view model in which I am storing a DateTime but in my view using a JQUERY datetimepicker, time only:
ViewModel
[DataType(DataType.Time)]
public DateTime? MondayFrom { get; set; }
[DataType(DataType.Time)]
public DateTime? MondayTo { get; set; }
As it stands, when the Create method gets called it is using todays date plus the time selected from the timepicker.
As I am not particularly concerned with the Date part of the DateTime, I want to change the day, month & year to 01/01/1900 or something less specific than the date the record was written, before the record is created, this is purely to avoid any confusion in the future.
I don't want to get bogged down on whether this is the right thing to do or not.
I'm struggling to get a handle on the Date part of the DateTime, see below:
public void CreateClub(Club club)
{
foreach (var item in club.MeetingDays)
{
// change Date part to 01/01/1900, leave the time as is..
}
_repository.CreateClub(club);
}
How might I floor the date part of the item but leave the time well alone?
Just use the TimeOfDay property to extract the time within the day, and add that to the date you want:
private static readonly DateTime BaseDate = new DateTime(1900, 1, 1);
var updatedDateTime = BaseDate + otherDateTime.TimeOfDay;
You could even write an extension method or two:
public static DateTime WithDate(this DateTime start, DateTime date)
{
// No need to use the Date property if you already know
// it will be midnight...
return date.Date + start.TimeOfDay;
}
public static DateTime WithFloorDate(this DateTime start)
{
return start.WithDate(FloorDate);
}
Of course, I'd suggest you use Noda Time where you can specify dates, times and date/time values (with or without a time zone or UTC offset0 separately, but that's a different conversation.
DateTime is immutable - you cant just change part of it. You can extract the time and add it to a "base" date:
for(int i=0; i < club.MeetingDays.Count; i++)
{
club.MeetingDays[i] = new DateTime(1900, 1, 1) + club.MeetingDays[i].TimeOfDay;
}
Note that you need a for loop so you can place the new value back in the collection. You could also use Linq:
club.MeetingDays = club.MeetingDays
.Select(t => new DateTime(1900, 1, 1) + t.TimeOfDay)
.ToList();
Assuming that club.MeetingDays is a List<Datetime>

How to change only the date portion of a DateTime, while keeping the time portion?

I use many DateTime in my code. I want to change those DateTimes to my specific date and keep
time.
1. "2012/02/02 06:00:00" => "2015/12/12 : 06:00:00"
2. "2013/02/02 12:00:00" => "2015/12/12 : 12:00:00"
I use this style to change, but it seem not the good way and I want to ask have any way to achieve this task.
DateTime newDateTime = new DateTime(2015,12,12,oldDateTime.Hour,oldDateTime.Minute,0);
A better way that preserves the seconds, milliseconds and smaller parts of the time would be:
DateTime newDateTime = new DateTime(2015,12,12) + oldDateTime.TimeOfDay;
Or you could make an extension method to apply a new Date to an existing DateTime and, at the same time, not trust the new date to be without a TimeOfDay on it:-
public static DateTime WithDate (this DateTime datetime, DateTime newDate)
{
return newDate.Date + datetime.TimeOfDay;
}
IMHO DateTime is one of the weakest parts of .NET. For example, a TimeSpan is not the same as a TimeOfDay nor can it represent a 'TimePeriod' (in months) - these are three separate concepts and mixing them up was a poor choice. Moving to DateTimeOffset is generally preferred or to the excellent Noda time library.
With the information you have given, I think this method is fine. If you want to avoid rewriting the oldDateTime.Hour,oldDateTime.Minute,0 piece often, you could create your own static class to simplify the method calls.
In your regular application:
class Program
{
static void Main(string[] args)
{
DateTime time = DateTime.Now;
DateTime newDateTime = MyDateTimeUtil.CreateDateFromTime(2015, 12, 12, time);
}
}
The static class that creates the DateTime value:
public static class MyDateTimeUtil
{
public static DateTime CreateDateFromTime(int year, int month, int day, DateTime time)
{
return new DateTime(year, month, day, time.Hour, time.Minute, 0);
}
}

How do i assign back the DateTime.Now from a string?

The code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime.Now = time;
}
time now for example show the saved datetime.now could be minute ago or an hour ao.
the datetime.now is saved after my program is finished to make an operation.
dt = the current datetime now i use this method in the constructor.
What i want to do is to calculate the time that have been passed between the last saved datetime.now(time) and the current datetime.now(dt).
If the time that have been passed is 20 minutes or more enable true a button.
You cannot set DateTime.Now You need to create an instance of the DateTime object.
Then to get the difference you can say
TimeSpan diff = DateTime.Now - MyDateTime;
This has a property called TotalMinutes that you can use for your check.
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
You can try this code
DateTime date;
if (DateTime.TryParse(time, out date))
{
TimeSpan diff = date - dt;
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
}
Every time you run this method you need to persist the value somewhere. I'm going to call that variable _lastTime. That's going to be a DateTime. Further, you'll need a variable for the actual elapsed time between those two, we'll call that _elapsedTime. That's going to be a TimeSpan. With that in mind, consider this code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
var dt = DateTime.Parse(time);
_elapsedTime = dt.Subtract(_elapsedTime);
_lastTime = dt;
}
You get an instance of a DateTime from a string using Parse
DateTime dt = DateTime.Parse(time)
and then you get get the time Now using
DateTime.UtcNow; or DateTime.Now;
and subtract one from the other and format as appropriate for you output
You can do this using TimeSpan.
you need to get the Difference in Minutes
DateTime dt1;//get your first date
TimeSpan duration = DateTime.Now - dt1;
if(duration.Minutes>20)
Button1.Enabled=true;
I think your looking for this:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime lastTime = DateTime.Parse(time);
if (DateTime.Now - lastTime > new TimeSpan(0, 20, 0))
{
//It's passed more than 20mins from last save.
}
}
You can check the time elapsed by using the TimeSpan class.
private void beginOperstionChecker(DateTime dt)
{
if(TimeSpan.FromMinutes(20) == DateTime.Now - dt)
{
//do your stuff here
}
}

How do I convert a 12 hour time string into a C# TimeSpan?

When a user fills out a form, they use a dropdown to denote what time they would like to schedule the test for. This drop down contains of all times of the day in 15 minute increments in the 12 hour AM/PM form. So for example, if the user selects 4:15 pm, the server sends the string "4:15 PM" to the webserver with the form submittion.
I need to some how convert this string into a Timespan, so I can store it in my database's time field (with linq to sql).
Anyone know of a good way to convert an AM/PM time string into a timespan?
You probably want to use a DateTime instead of TimeSpan. You can use DateTime.ParseExact to parse the string into a DateTime object.
string s = "4:15 PM";
DateTime t = DateTime.ParseExact(s, "h:mm tt", CultureInfo.InvariantCulture);
//if you really need a TimeSpan this will get the time elapsed since midnight:
TimeSpan ts = t.TimeOfDay;
Easiest way is like this:
var time = "4:15 PM".ToTimeSpan();
.
This takes Phil's code and puts it in a helper method. It's trivial but it makes it a one line call:
public static class TimeSpanHelper
{
public static TimeSpan ToTimeSpan(this string timeString)
{
var dt = DateTime.ParseExact(timeString, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
return dt.TimeOfDay;
}
}
Try this:
DateTime time;
if(DateTime.TryParse("4:15PM", out time)) {
// time.TimeOfDay will get the time
} else {
// invalid time
}
I like Lee's answer the best, but acermate would be correct if you want to use tryparse. To combine that and get timespan do:
public TimeSpan GetTimeFromString(string timeString)
{
DateTime dateWithTime = DateTime.MinValue;
DateTime.TryParse(timeString, out dateWithTime);
return dateWithTime.TimeOfDay;
}
Try:
string fromServer = <GETFROMSERVER>();
var time = DateTime.Parse(fromServer);
That gets you the time, if you create the end time as well you can get Timespans by doing arithmetic w/ DateTime objects.

Categories