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 9 years ago.
Improve this question
I'm trying to add the phones current time to my date time list. I need it to be able to subtract with the ticks. I have tried using phonecurrentime.ToString("dd hh:mm"); but because it's a string there are no ticks and all sorts of errors!
I need it to work with DateTime.now.
Here is my code:
InitializeComponent();
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
// This is the date you want to find the closest one to
fileDate = DateTime.Now;
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
Darren Davies above is correct.
You can add/subtract datetime objects. The result is of type TimeSpan, which lets you easily compare date and/or time differences.
Also, you should give a name to each date you add to your list (assign to a variable then add to list). A month later you won't remember what each day meant ;)
if you have a string and want to convert it to DateTime you can use
CultureInfo cf = new CultureInfo("en-us");
if(DateTime.TryParseExact("12 12:45", "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
// your code
}
and your code would look like:
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
CultureInfo cf = new CultureInfo("en-us");
string timeToParse = phonecurrentime.ToString("dd hh:mm");
if(DateTime.TryParseExact(timeToParse, "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
}
if you want to compare the time part of the dateTime you can use TimeOfDay property:
TimeSpan ts = DateTime.Now.TimeOfDay;
foreach (DateTime date in theDates)
{
long diff = Math.Abs(ts.Ticks - date.TimeOfDay.Ticks);
if (diff < min)
{
min = diff;
closestDate = date;
}
}
fileDate = phonecurrentime.ToString("dd hh:mm");
Will not compile. fileDate is a DateTime object. You need to assign it to another DateTime object, not a string.
If phonecurrenttime is a DateTime you can ommit the .ToString() method.
fileDate = phonecurrenttime;
Edit
From your comment, if you simply want to assign the current ddate/time to fileDate you can use DateTime.Now:
fileDate = DateTime.Now;
Related
How to subtract "year=117 month=1 day=28 hour=7 min=43 sec=10" from a DateTime in c#?
I have already tried like below
split the string using regex.
add each item with -ve sign to a current DateTime value.
But I think it's not an efficient way.
Can anyone help me?
You can use below Code as per you requirement to get desired Result. Replace your Date, Time, year values in "new System.DateTime(1996, 6, 3, 22, 15, 0);"
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
you can try DateTime's subtraction.
for that first you have to make valid DateTime object from your information and then subtract that date from current date.
see below code,
int year = 117, month = 01, day = 28;
int hour = 07, minute = 43, second = 10;
DateTime timeToSubtract =
new DateTime(year > 0? year : 1, month > 0 ? month : 1, day > 0 ? day : 1, hour, minute, second);
DateTime subtractedDate =
new DateTime((DateTime.Now - timeToSubtract).Ticks);
as you can see, we are creating a date time object with information we have (date and time which should be subtracted form current date time) by, new DateTime(year, month, day, hour, minute, second) and then subtracting this from DateTime.Now, and then creating final date out of result of this subtraction.
here in last line we are creating a date (of past). this date is of specified time ago.
I'm trying to make a function in C# that returns the week difference between two dates. Its goal is to provide the same result of:
select datediff(ww,'2018-04-13','2018-04-16') as diff
In the example above there is only 3 days between these dates, but they are in different weeks, so the result should be 1.
I've tried to use .TotalDays but it's not working properly. I also tried .GetWeekOfYear but it won't return correctly when the year of the dates are different. I've seem many questions here on StackOverflow and on other forums and so far none of them match my case. This is the function I'm trying to far:
public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd) {
// Doesn't work
var val = ((dtEnd - dtStart).TotalDays / 7);
val = Math.Ceiling(val);
return Convert.ToInt32(val);
// Doesn't work well between years
DateTimeFormatInfo dinfo = DateTimeFormatInfo.CurrentInfo;
var x = dinfo.Calendar.GetWeekOfYear(dtStart, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
var y = dinfo.Calendar.GetWeekOfYear(dtEnd, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
return y - x;
}
In the first part of my function, I tried what is described in this post. It didn't work
Can you help me?
Thanks in advance.
First figure how many days there are between the two dates. Divide the number of days by 7 to get full weeks.
Now figure out if there's an extra week to be counted by finding taking the number of days modulus 7 to get any remaining days. If the first date plus remaining days falls in a different week, add an extra week on to the count.
void Main()
{
var first = new DateTime(2018, 04, 13);
var second = new DateTime(2018, 04, 16);
Console.WriteLine(weekDiff(first, second));
}
public int weekDiff(DateTime d1, DateTime d2, DayOfWeek startOfWeek = DayOfWeek.Monday)
{
var diff = d2.Subtract(d1);
var weeks = (int)diff.Days / 7;
// need to check if there's an extra week to count
var remainingDays = diff.Days % 7;
var cal = CultureInfo.InvariantCulture.Calendar;
var d1WeekNo = cal.GetWeekOfYear(d1, CalendarWeekRule.FirstFullWeek, startOfWeek);
var d1PlusRemainingWeekNo = cal.GetWeekOfYear(d1.AddDays(remainingDays), CalendarWeekRule.FirstFullWeek, startOfWeek);
if (d1WeekNo != d1PlusRemainingWeekNo)
weeks++;
return weeks;
}
static void Main(string[] args)
{
DateTime date1 = new DateTime(2018, 04, 18);
DateTime date2 = new DateTime(2018, 04, 19);
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 18), new DateTime(2018, 04, 18)))); // 0
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 22), new DateTime(2018, 04, 23)))); // 1
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 16), new DateTime(2018, 04, 22)))); // 0
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 18), new DateTime(2018, 05, 03)))); // 2
}
private static int GetDiff(DateTime date1, DateTime date2)
{
date1 = SetDayToMonday(date1);
date2 = SetDayToMonday(date2);
return (int)((date2 - date1).TotalDays / 7);
}
private static DateTime SetDayToMonday(DateTime date)
{
var weekDay = date.DayOfWeek;
if (weekDay == DayOfWeek.Sunday)
return date.AddDays(-6);
else
return date.AddDays(-((int)weekDay-1));
}
First, set the day to the monday of the current week. Then count all full weeks(= /7 days as int). Easy as it is, it works probably across weeks and years.
See if this works. There could be more use cases that this doesn't cover, and the solution depends on how you define a week boundary (this assumes Sunday-Monday based on a comment above).
// Output:
// Weeks between 12/28/2017 and 1/10/2018: 2
// Weeks between 4/13/2018 and 4/16/2018: 1
// Weeks between 4/21/2018 and 4/22/2018: 0
// Weeks between 4/22/2018 and 4/23/2018: 1
void Main()
{
var datePairs = new List<KeyValuePair<DateTime, DateTime>>();
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2017, 12, 28), new DateTime(2018, 1, 10)));
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 13), new DateTime(2018, 4, 16)));
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 21), new DateTime(2018, 4, 22)));
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 22), new DateTime(2018, 4, 23)));
foreach (var datePair in datePairs)
{
var string1 = datePair.Key.ToShortDateString();
var string2 = datePair.Value.ToShortDateString();
Console.WriteLine($"Weeks between {string1} and {string2}: {GetWeekDiff(datePair.Key, datePair.Value)}");
}
}
public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd)
{
var totalDays = (dtEnd - dtStart).TotalDays;
var weeks = (int)totalDays / 7;
var hasRemainder = totalDays % 7 > 0;
if (hasRemainder)
{
if (!(dtStart.DayOfWeek.Equals(DayOfWeek.Saturday) && dtEnd.DayOfWeek.Equals(DayOfWeek.Sunday)))
{
weeks++;
}
}
return weeks;
}
Maybe it can help
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
Get the correct week number of a given date
Can't comment yet and already used a flag on this post on something I believed to be similar. Here is another post I found that appears to align with the solution you are trying to create:
Get the number of calendar weeks between 2 dates in C#
This is my implementation to solve a similar problem, I haven't tested in thoroughly but it seems to work.
var dt1 = DateTime.Today.AddDays(-30);
var dt2 = DateTime.Today;
var noOfDays =(int) (dt2 - dt1).TotalDays;
int reminder;
var weeks = Math.DivRem(noOfDays, 7, out reminder);
weeks = reminder > 0 ? weeks + 1 : weeks;
It returns 1 week for 6 days or less gap, which is exactly what I needed.
Given this datetime of January 1 2015 at 23:00 hours:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
And given the int 6, which is the desired hour, how do I return the first following datetime where the hour is 6? In this case, someDate and 6 would return a new DateTime of January 2 2015 at 06:00 hours.
I would simply add the hours to the original date and add another day if the result is before the original time:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);
You just have to add one day to the date and six hours to the result:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddDays(1).AddHours(6);
Note the use of Date property - it will give you the start od the day and from there it's easy to navigate forward.
Try this:
while(someDate.Hour != 6){
someDate = someDate.AddHours(1);
}
Assuming you meant 24h clock, you can try this:
public DateTime GetDate(DateTime someDate,int hour)
{
return someDate.Hour>=hour? someDate.Date.AddDays(1).AddHours(6):someDate.Date.AddHours(6);
}
Something like this should do it:
public DateTime FollowingHour(DateTime start, int hour)
{
DateTime atHour = start.Date.AddHours(6);
if(atHour < start)
{
atHour += TimeSpan.FromDays(1);
}
return atHour;
}
Tables dt like this:
index StartDate EndDate
1 2015/03/23 22:00 2015/03/23 23:00
2 2015/03/23 22:00 2015/03/23 22:00
3 2015/03/23 22:00 2015/03/23 22:00
I have set:
lookupedit1.Properties.ValueMember = "StartDate";
lookupedit1.Properties.DisplayMember = "StartDate";
So, the value has show OK, long date Type, but i want the DisplayMemeber like short date type.
I have try any of below, but it's havn't work expectly.
lookupedit1.Properties.Mask.EditMask = "yyyy-MM-dd";
lookupedit1.Properties.DisplayFormat.FormatString = "yyyy-MM-dd";
lookupedit1.Properties.EditFormat.FormatString = "yyyy-MM-dd";
How can i resolve my questions?
i want the DisplayMemeber like short date type
You can use the standard d display-format string for short date (culture specific, described in the Standard Date and Time Format Strings document in MSDN.). To specify formatting-behavior you should add the specific column into the LookUp edit:
lookUpEdit1.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo()
{
FieldName = "StartDate",
FormatType = DevExpress.Utils.FormatType.DateTime,
FormatString = "d" // short date
});
lookUpEdit1.Properties.DataSource = new List<Order> {
new Order(){ StartDate = new DateTime(2015, 03, 23, 23, 0, 0) },
new Order(){ StartDate = new DateTime(2015, 03, 24, 23, 0, 0) },
new Order(){ StartDate = new DateTime(2015, 03, 25, 23, 0, 0) },
};
To setup display-behavior while editing you can use the editor's Mask :
lookUpEdit1.Properties.Mask.EditMask = "d"; // short date
lookUpEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime;
lookUpEdit1.Properties.Mask.UseMaskAsDisplayFormat = true;
In C# 3.0, how do I get the seconds since 1/1/2010?
Goes like this:
TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01);
MessageBox.Show(test.TotalSeconds.ToString());
For one liner fun:
MessageBox.Show((DateTime.Now - new DateTime(2010, 01, 01))
.TotalSeconds.ToString());
You can substract 2 DateTime instances and get a TimeSpan:
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
Just to avoid timezone issues
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
It's really a matter of whose 2010-Jan-01 you're using and whether or not you wish to account for daylight savings.
//I'm currently in Central Daylight Time (Houston, Texas)
DateTime jan1 = new DateTime(2010, 1, 1);
//days since Jan1 + time since midnight
TimeSpan differenceWithDaylightSavings = DateTime.Now - jan1;
//one hour less than above (we "skipped" those 60 minutes about a month ago)
TimeSpan differenceWithoutDaylightSavings = (DateTime.UtcNow - jan1.ToUniversalTime());
//difference for those using UTC and 2010-Jan-01 12:00:00 AM UTC as their starting point
// (today it's 5 hours longer than differenceWithDaylightSavings)
TimeSpan utcDifference = (DateTime.UtcNow - new DateTime(2010, 1, 1));
Difference with Daylight Savings: 105.15:44:09.7003571
Difference without Daylight Savings: 105.14:44:09.7003571
UTC Difference: 105.20:44:09.7003571
To get the seconds, use the TotalSeconds property off the TimeSpan object.
protected void Page_Load(object sender, EventArgs e)
{
SecondsSinceNow(new DateTime(2010, 1, 1, 0, 0, 0));
}
private double SecondsSinceNow(DateTime compareDate)
{
System.TimeSpan timeDifference = DateTime.Now.Subtract(compareDate);
return timeDifference.TotalSeconds;
}
DateTime t1 = DateTime.Now;
DateTime p = new DateTime(2010, 1, 1);
TimeSpan d = t1 - p;
long s = (long)d.TotalSeconds;
MessageBox.Show(s.ToString());