Dart/Flutter get first DateTime of this week [duplicate] - datetime

This question already has answers here:
How to get start of or end of week in dart
(8 answers)
Closed 1 year ago.
Using flutter on android I am trying to get the first date of current week. For example today is 13/7/2020, assuming week starts from Saturday the first date of current week will be 11/7/2020.
This for example to get first date of month
DateTime firstDay = new DateTime(
DateTime.now().year,
DateTime.now().month,
1,
); //get first date this month
The end goal is to get timestamp of that date and fetch entries from sqflite database that is higher than that.

If Sunday is your first day of week.
var d = DateTime.now();
var weekDay = d.weekday;
var firstDayOfWeek = d.subtract(Duration(days: weekDay));
According to Flutter docs weekDay returns
The day of the week [monday]..[sunday].
In accordance with ISO 8601
a week starts with Monday, which has the value 1.
if Monday is first day of week then
var firstDayOfWeek = d.subtract(Duration(days: weekDay - 1));

For Sunday:
DateTime today = DateTime.now();
DateTime _firstDayOfTheweek =
today.subtract(new Duration(days: today.weekday));
print(_firstDayOfTheweek.day);
For Monday:
DateTime _firstDayOfTheweek =
today.subtract(new Duration(days: today.weekday - 1));
print(_firstDayOfTheweek.day);
For Saturday:
DateTime _firstDayOfTheweek =
today.subtract(new Duration(days: today.weekday + 1));
print(_firstDayOfTheweek.day);

The DateTime class stores int constants for the day of the week which you could use to calculate the start date you need. Something like this should work:
void main() {
var startOfWeek = DateTime.saturday;
var currentDate = DateTime.now();
var daysSince = currentDate.weekday + (DateTime.sunday - startOfWeek);
var result = currentDate.subtract(Duration(days: daysSince));
print('Date at start of week is $result');
}

To get different dates of different days in a week. We can use this isoweek package for this. We can use like this :-
Week currentWeek = Week.current();
Week weekFromIso = Week.fromISOString(currentWeek.toString());
print('Week from ISO string: $weekFromIso');
DateTime firstDay= weekFromIso.day(0);
String formattedDateFirst = DateFormat('EEE, d MMM').format(firstDay);
DateTime secondDay= weekFromIso.day(1);
String formattedDateSecond = DateFormat('EEE, d MMM').format(secondDay);

Related

How to get start of or end of week in dart

How can I get the start of or end of a week in dart? An example is if three days ago was a Monday, and today is a Wednesday, how can I find the start of the week using dart, that is on Monday
You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:
void main() {
final date = DateTime.parse('2019-10-08 15:43:03.887');
print('Date: $date');
print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
UPDATE
Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)
Dart DateTimes have a weekday getter which is 1 for Monday and 7 for Sunday. Using that, I would do:
DateTime mostRecentSunday(DateTime date) =>
DateTime(date.year, date.month, date.day - date.weekday % 7);
to get the most recent Sunday (which is the start of the current week if the week starts on a Sunday), and
DateTime mostRecentMonday(DateTime date) =>
DateTime(date.year, date.month, date.day - (date.weekday - 1));
for the most recent Monday (which is then the start of the current week if the week starts on a Monday).
You can generalize to
/// The [weekday] may be 0 for Sunday, 1 for Monday, etc. up to 7 for Sunday.
DateTime mostRecentWeekday(DateTime date, int weekday) =>
DateTime(date.year, date.month, date.day - (date.weekday - weekday) % 7);
If you are going to be using the results as calendar dates, I'd used DateTime.utc as the constructor instead. (Always use UTC for calendar dates, then you can do day-based arithmetic on them safely).
I'd even consider using DateTime.utc in any case because it avoids any potential issues with a daylight saving that starts at midnight (rare, but with time zones, even unlikely things tend to have happened somewhere at some point).
The way you do this will probably depend on what your app's localization is. If you want to treat Sunday as the start of the week, you would do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay));
If you are treating Monday as the start, then do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay - 1));
MaterialLocalizations
If you're using Dart in Flutter, you can use the MaterialLocalizations class to get the index of the first day of the week (0 = Sunday, 6 = Saturday). This should help you decide which method from above that you should use.
The example given for the firstDayOfWeekIndex property is a good reference:
var localizations = MaterialLocalizations.of(context);
// The name of the first day of week for the current locale.
var firstDayOfWeek = localizations.narrowWeekdays[localizations.firstDayOfWeekIndex];
The MaterialLocalizations class comes with a ton of built in methods to format and display DateTimes.
dateTime: 2021-01-26 11:21:05.429320
formatFullDate: Tuesday, January 26, 2021
formatCompactDate: 01/26/2021
formatMediumDate: Tue, Jan 26
formatShortDate: Jan 26, 2021
formatShortMonthDay: Jan 26
formatMonthYear: January 2021
formatYear: 2021
If none of these fit your needs, you can also use the DateFormat class to specify how the DateTime should be displayed. It's important to note that the DateFormat class indexes days differently where 1 = Monday and 7 = Sunday.
DateFormat.yMMMd().format(new DateTime.now()) // Jan 26, 2021
DateFormat(DateFormat.ABBR_MONTH_DAY).format(now) // Jan 26
DateFormat(DateFormat.WEEKDAY).format(now) // Tuesday
FIRST DAY OF THE WEEK
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
LAST DAY OF THE WEEK
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime
.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
LAST DAY OF THE MONTH
DateTime findLastDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month + 1, 0);
}
FIRST DAY OF THE MONTH
DateTime findFirstDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month, 1);
}
LAST DAY OF THE YEAR
DateTime findLastDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 12, 31);
}
FIRST DAY OF THE YEAR
DateTime findFirstDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 1, 1); }
Dart/Flutter – How to find the first date and the last date of a week
1. Find the first date of the week
/// Find the first date of the week which contains the provided date.
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
2. Find the last date of the week
/// Find last date of the week which contains provided date.
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
Testing
void main() {
// Find first date and last date of THIS WEEK
DateTime today = DateTime.now();
print(findFirstDateOfTheWeek(today));
print(findLastDateOfTheWeek(today));
// Find first date and last date of any provided date
DateTime date = DateTime.parse('2020-11-24');
print(findFirstDateOfTheWeek(date));
print(findLastDateOfTheWeek(date));
}
// Output
2020-11-23 06:54:42.865446
2020-11-29 06:54:42.865446
2020-11-23 00:00:00.000
2020-11-29 00:00:00.000
None of the above worked for me but #JoeMuller gave an interesting piece of info on the material localizations, which led me to find out that for what i want, sunday in date.weekday should be 0 took a while to figure it out many thanks to joe and #julemand101 I have this for UK calendar starting from sunday and ending on saturday
void main() {
final date = DateTime.parse('2021-08-01');
print('Date: $date');
final weekDay = date.weekday == 7 ? 0 : date.weekday;
print('Start of week: ${getDate(date.subtract(Duration(days: weekDay)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - weekDay - 1)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
I have 2 function:
DateTime getStartTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day);
return dateTime.subtract(Duration(days: currentDate.weekday - 1));
}
DateTime getEndTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day, 23, 59, 59, 999);
return dateTime.add(Duration(days: DateTime.daysPerWeek - currentDate.weekday));
}
Below is the code which should work fine in most cases.
We can get start and end of the week like this:-
To get the first day of the week for a date use the below function.
Like Sunday (Also known as 7 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getFirstDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Sunday from the provided date
// By going back a number of weekdays from the current date to reach Sunday
DateTime firstDayOfWeekInUTC;
// If current date is not Sunday subtract days to reach Sunday
if (currentWeekDayInUTC != DateTime.sunday) {
firstDayOfWeekInUTC =
dateTimeInUTC.subtract(Duration(days: currentWeekDayInUTC));
}
// If current date is Sunday use it as the first day of week
else {
firstDayOfWeekInUTC = dateTimeInUTC;
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime firstDayOfWeekInLocal = DateTime(firstDayOfWeekInUTC.year,
firstDayOfWeekInUTC.month, firstDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return firstDayOfWeekInUTC;
} else {
return firstDayOfWeekInLocal;
}
}
To get the last day of the week for a date use the below function.
Like Saturday (Also known as 6 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getLastDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Saturday from the provided date
// By going forward a number of weekdays from the current date to reach Saturday
DateTime lastDayOfWeekInUTC;
// If current date is not Sunday add days enough to reach Saturday
if (currentWeekDayInUTC != DateTime.sunday) {
lastDayOfWeekInUTC = dateTimeInUTC
.add(Duration(days: DateTime.saturday - currentWeekDayInUTC));
}
// If current date is Sunday add days UpTo saturday
else {
lastDayOfWeekInUTC = dateTimeInUTC.add(Duration(days: DateTime.saturday));
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime lastDayOfWeekInLocal = DateTime(lastDayOfWeekInUTC.year,
lastDayOfWeekInUTC.month, lastDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return lastDayOfWeekInUTC;
} else {
return lastDayOfWeekInLocal;
}
}

When i get the difference between endDate.millisecondsSinceEpoch and startDate.millisecondsSinceEpoch it gives me the result plus 2 hours?

I want to get the difference between endDate and startDate
int endDate = DateTime.parse("2019-01-31 09:35:00").millisecondsSinceEpoch;
int startDate = DateTime.parse("2019-01-31 09:30:00").millisecondsSinceEpoch;
Then i get the diffrernce
int distance = endDate - startDate;
After that i convert distance to DateTime
DateTime newTime = DateTime.fromMillisecondsSinceEpoch(distance);
Result
02:05:00
Expected Output
00:05:00
Where is the mistake ?
Date/Time calculations in local timezone are prone to mistakes.
Convert to UTC first:
int endDate =
DateTime.parse("2019-01-31 09:35:00").toUtc().millisecondsSinceEpoch;
int startDate =
DateTime.parse("2019-01-31 09:30:00").toUtc().millisecondsSinceEpoch;
int distance = endDate - startDate;
DateTime newTime = DateTime.fromMillisecondsSinceEpoch(distance, isUtc: true);
print('result: $newTime');
result: 1970-01-01 00:05:00.000Z
But as mentioned in the comment below your question, Duration would be better for that purpose.
Try this very simple package, Jiffy that is inspired by momentjs
Looks like you are trying to get the difference in minutes. See below
var startDate = Jiffy(DateTime(2019, 1, 31, 9, 35));
var endDate = Jiffy(DateTime(2019, 1, 31, 9, 30));
print(startDate.diff(endDate, Units.MINUTE)); // 5 minutes
You can also get the difference in the following units, years, months, weeks, days, hours, minutes, seconds and milliseconds. Also, see below
print(startDate.diff(endDate, Units.SECOND)); // 300 seconds
print(startDate.diff(endDate, Units.MILLISECOND)); // 300000 milliseconds

Get Week Number from Given Date in ASP.NET [duplicate]

This question already has answers here:
How can I calculate/find the week-number of a given date?
(7 answers)
Closed 8 years ago.
I have date like 08/31/2013 and i want in which week given date falls.So please help me how can i achieved it.For e.g give date falls in 5th week of August.
Try
var currCulture = CultureInfo.CurrentCulture;
var weekNo = currCulture.Calendar.GetWeekOfYear(
new DateTime(2014, 28, 03), //Any date
currCulture.DateTimeFormat.CalendarWeekRule,
currCulture.DateTimeFormat.FirstDayOfWeek);
Found this here. Check if helps.
DateTime dt = DateTime.Now;
int weekOfMonth = (dt.Day + ((int)dt.DayOfWeek)) / 7 + 1;
DateTime dt = DateTime.Today;
CultureInfo ci = CultureInfo.CurrentCulture;
int weekNum = ci.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
weekNum = weekNum / 12;
string weekday = dt.DayOfWeek.ToString();
With this code you will be able to get week number and week day of any date.....

Given a date how to get Sunday & Saturday of that week

I want to get the Sunday & Saturday of the week from which a date is provided.
I have access to the following functions only:
getDate() returns a number from 0-6 (0 being sunday)
getDay() returns a number from 1-31
getMonth() returns a number from 0-11
getFullYear() returns the current year
I am doing this on titanium.
Per your description above, I came up with:
var sat = new Date(input.getFullYear(), input.getMonth(), 6 - input.getDate() + getDay());
var sun = new Date(input.getFullYear(), input.getMonth(), getDay() + (input.getDate() - 6));
If I follow the MDN doc, I come up with (works in Ti too):
var sat = new Date(input.getFullYear(), input.getMonth(), 6 - input.getDay() + input.getDate());
var sun = new Date(input.getFullYear(), input.getMonth(), input.getDate() + (input.getDay() - 6));
Where input is a javascript Date object.
The date object will take care or changing the month and/or year if necessary.
Hope this helps.

How to calculate the number of weeks in a month

I want to calculate the total no of weeks in current month. Starting from Sunday or Monday.
Is it possible to do in Qt
I would say this problem is not specific to Qt, but Qt can help you with the QDate class.
With this class you can get the current month :
QDate CurrentDate = QDate::currentDate();
The number of days of a given month :
CurrentDate.daysInMonth();
For the number of week calculation, it depends if you only want the number of full weeks in a month, or the number of weeks, taking partial weeks into account.
For the latter, here is how I would do it (considering the week starts on monday) :
const DAYS_IN_WEEK = 7;
QDate CurrentDate = QDate::currentDate();
int DaysInMonth = CurrentDate.daysInMonth();
QDate FirstDayOfMonth = CurrentDate;
FirstDayOfMonth.setDate(CurrentDate.year(), CurrentDate.month(), 1);
int WeekCount = DaysInMonth / DAYS_IN_WEEK;
int DaysLeft = DaysInMonth % DAYS_IN_WEEK;
if (DaysLeft > 0) {
WeekCount++;
// Check if the remaining days are split on two weeks
if (FirstDayOfMonth.dayOfWeek() + DaysLeft - 1 > DAYS_IN_WEEK)
WeekCount++;
}
This code has not been fully tested and is not garanteed to work !
floor(Number of Days / 7)
QDate::weekNumber can give you the number of the week in the year.
Here is an example of how to use it to obtain the number of weeks in a month, including those shorter than seven days:
QDate dateCurrent = QDate::currentDate();
int year = dateCurrent.year(), month = dateCurrent.month(),
daysInMonth = dateCurrent.daysInMonth(), weeksInMonth;
weeksInMonth = QDate(year, month, daysInMonth).weekNumber()
- QDate(year, month, 1).weekNumber() + 1;
Some months have 4 weeks and others have 5. Qt states that:
In accordance with ISO 8601, weeks start on Monday and the first Thursday of a year is always in week 1 of that year. Most years have 52 weeks, but some have 53.
For that matter my first Thursday in a month is the starting point when counting the number of weeks in a month. The function below works for me:
int myClass::weeksInMonth(QDate cdate)
{
QDate sDte = QDate(cdate.year(),cdate.month(),1);
QDate eDte = QDate(cdate.year(),cdate.month(),cdate.daysInMonth());
int wks = 0;
for(QDate stD = sDte; stD <= eDte; stD = stD.addDays(1)){
if(stD.dayOfWeek() == Qt::Thursday)++wks;
}
return wks;
}
Here's a function that wraps the top answer for PyQt5. However the ISO 8601 definition for week 01 is the week with the first Thursday of the Gregorian year; this solution will give a negative number of weeks on dec and jan on certain years..
def weeksInMonth(date: QDate):
year = date.year(), month = date.month()
daysInMonth = date.daysInMonth()
return QDate(year, month, daysInMonth).weekNumber()[0] - QDate(year, month, 1).weekNumber()[0] + 1

Resources