I have a date returned by a json, it is in the following variable as string:
val dateEvent = "2019-12-28 21:00:00"
The calculation I need is to know how many days hours minutes are left with the current date.
I have found some solutions but these use as input "2019-12-28" and I have my format with the time included.
java.time
Since Java 9 you can do (sorry that I can write only Java code):
DateTimeFormatter jsonFormatter = DateTimeFormatter.ofPattern("u-M-d H:mm:ss");
String dateEvent = "2019-12-28 21:00:00";
Instant eventTime = LocalDateTime.parse(dateEvent, jsonFormatter)
.atOffset(ZoneOffset.UTC)
.toInstant();
Duration timeLeft = Duration.between(Instant.now(), eventTime);
System.out.format("%d days %d hours %d minutes%n",
timeLeft.toDays(), timeLeft.toHoursPart(), timeLeft.toMinutesPart());
When I ran the code just now, the output was:
145 days 4 hours 19 minutes
In Java 6, 7 and 8 the formatting of the duration is a bit more wordy, search for how.
Avoid SimpleDateFormat and friends
The SimpleDateFormat and Date classes used in the other answer are poorly designed and long outdated. In my most honest opinion no one should use them in 2019. java.time, the modern Java date and time API, is so much nicer to work with.
Use the following function:
fun counterTime(eventtime: String): String {
var day = 0
var hh = 0
var mm = 0
try {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val eventDate = dateFormat.parse(eventtime)
val cDate = Date()
val timeDiff = eventDate.time - cDate.time
day = TimeUnit.MILLISECONDS.toDays(timeDiff).toInt()
hh = (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day.toLong())).toInt()
mm =
(TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))).toInt()
} catch (e: ParseException) {
e.printStackTrace()
}
return if (day == 0) {
"$hh hour $mm min"
} else if (hh == 0) {
"$mm min"
} else {
"$day days $hh hour $mm min"
}
}
counterTime(2019-08-27 20:00:00)
This returns 24 days 6 hour 57 min
Note: The event date should always be a future date to the current date.
Related
How i can get default date if more than 6 hours have passed?
how i get relative time
let date = 24-05-2021 13:55
const relativeTime = moment(date, 'DD-MM-YYYY HH:mm').fromNow()
I saw examples but I can't figure it out, my English is very bad
Thanks for the help, I solved the problem like this, if someone needs a solution.
const date = data.date
let dateNow = moment(new Date(), 'DD-MM-YYYY HH:mm')
let postDate = moment(date, 'DD-MM-YYYY HH:mm')
let result = dateNow.diff(postDate, 'hours')
console.log(result)
if (result <= 6) {
/*if less than 6 hours have passed i return relative date format 2 hours ago*/
const relativeTime = moment(date, 'DD-MM-YYYY HH:mm').fromNow()
data.date = relativeTime
return { data }
}else {
/* if more than 6 hours have passed i return original date format 25-05-2021 14:01*/
return { data }
}
I'm looking for a way to use DateTime to parse two dates, to show the difference.
I want to have it on the format: "X years, Y months, Z days".
For JS, we have momentjs library and following code::
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'year');
b.add(years, 'years');
var months = a.diff(b, 'months');
b.add(months, 'months');
var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days
Is there similar library available for dart that can help achieve this usecase?
I think it is not possible to do exactly what you want easily with DateTime. Therefore you can use https://pub.dev/packages/time_machine package that is quite powerful with date time handling:
import 'package:time_machine/time_machine.dart';
void main() {
LocalDate a = LocalDate.today();
LocalDate b = LocalDate.dateTime(DateTime(2022, 1, 2));
Period diff = b.periodSince(a);
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}");
}
for hours/minutes/seconds precision:
import 'package:time_machine/time_machine.dart';
void main() {
LocalDateTime a = LocalDateTime.now();
LocalDateTime b = LocalDateTime.dateTime(DateTime(2022, 1, 2, 10, 15, 47));
Period diff = b.periodSince(a);
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}; hours: ${diff.hours}; minutes: ${diff.minutes}; seconds: ${diff.seconds}");
}
What you are looking for is the Dart DateTime class
You can get close to what you want in moment.js with
main() {
var a = DateTime.utc(2015, 11, 29);
var b = DateTime.utc(2007, 06, 27);
var years = a.difference(b);
print(years.inDays ~/365);
}
There is no inYears or inMonths option for DateTime though that's why the year is divided in the print.
the difference function returns the difference in seconds so you have to process it yourself to days.
You could write an extension on duration class to format it:
extension DurationExtensions on Duration {
String toYearsMonthsDaysString() {
final years = this.inDays ~/ 365
// You will need a custom logic for the months part, since not every month has 30 days
final months = (this.inDays ~% 365) ~/ 30
final days = (this.inDays ~% 365) ~% 30
return "$years years $months months $days days";
}
}
The usage will be:
final date1 = DateTime()
final date2 = DateTime()
date1.difference(date2).toYearsMonthsDaysString()
You can use Jiffy Package for this like this
var jiffy1 = Jiffy("2008-10", "yyyy-MM");
var jiffy2 = Jiffy("2007-1", "yyyy-MM");
jiff1.diff(jiffy2, Units.YEAR); // 1
jiff1.diff(jiffy2, Units.YEAR, true);
You can calculate from the total number of days:
void main() {
DateTime a = DateTime(2015, 11, 29);
DateTime b = DateTime(2007, 06, 27);
int totalDays = a.difference(b).inDays;
int years = totalDays ~/ 365;
int months = (totalDays-years*365) ~/ 30;
int days = totalDays-years*365-months*30;
print("$years $months $days $totalDays");
}
Result is: 8 5 7 3077
I created my own class for Gregorian Dates, and I created a method which handle this issue, it calculates "logically" the difference between two dates in years, months, and days...
i actually created the class from scratch without using any other packages (including DateTime package) but here I used DateTime package to illustrate how this method works.. until now it works fine for me...
method to determine if it's a leap year or no:
static bool leapYear(DateTime date) {
if(date.year%4 == 0) {
if(date.year%100 == 0){
return date.year%400 == 0;
}
return true;
}
return false;
}
this is the method which calculates the difference between two dates in years, months, and days. it puts the result in a list of integers:
static List<int> differenceInYearsMonthsDays(DateTime dt1, DateTime dt2) {
List<int> simpleYear = [31,28,31,30,31,30,31,31,30,31,30,31];
if(dt1.isAfter(dt2)) {
DateTime temp = dt1;
dt1 = dt2;
dt2 = temp;
}
int totalMonthsDifference = ((dt2.year*12) + (dt2.month - 1)) - ((dt1.year*12) + (dt1.month - 1));
int years = (totalMonthsDifference/12).floor();
int months = totalMonthsDifference%12;
late int days;
if(dt2.day >= dt1.day) {days = dt2.day - dt1.day;}
else {
int monthDays = dt2.month == 3
? (leapYear(dt2)? 29: 28)
: (dt2.month - 2 == -1? simpleYear[11]: simpleYear[dt2.month - 2]);
int day = dt1.day;
if(day > monthDays) day = monthDays;
days = monthDays - (day - dt2.day);
months--;
}
if(months < 0) {
months = 11;
years--;
}
return [years, months, days];
}
the method which calculates the difference between two dates in months, and days:
static List<int> differenceInMonths(DateTime dt1, DateTime dt2){
List<int> inYears = differenceInYearsMonthsDays(dt1, dt2);
int difMonths = (inYears[0]*12) + inYears[1];
return [difMonths, inYears[2]];
}
the method which calculates the difference between two dates in days:
static int differenceInDays(DateTime dt1, DateTime dt2) {
if(dt1.isAfter(dt2)) {
DateTime temp = dt1;
dt1 = dt2;
dt2 = temp;
}
return dt2.difference(dt1).inDays;
}
usage example:
void main() {
DateTime date1 = DateTime(2005, 10, 3);
DateTime date2 = DateTime(2022, 1, 12);
List<int> diffYMD = GregorianDate.differenceInYearsMonthsDays(date1, date2);
List<int> diffMD = GregorianDate.differenceInMonths(date1, date2);
int diffD = GregorianDate.differenceInDays(date1, date2);
print("The difference in years, months and days: ${diffYMD[0]} years, ${diffYMD[1]} months, and ${diffYMD[2]} days.");
print("The difference in months and days: ${diffMD[0]} months, and ${diffMD[1]} days.");
print("The difference in days: $diffD days.");
}
output:
The difference in years, months and days: 16 years, 3 months, and 9 days.
The difference in months and days: 195 months, and 9 days.
The difference in days: 5945 days.
the answer is yes, you can easilly achieve it with DateTime class in Dart. See: https://api.dart.dev/stable/2.8.3/dart-core/DateTime-class.html
Example
void main() {
var moonLanding = DateTime(1969,07,20)
var marsLanding = DateTime(2024,06,10);
var diff = moonLanding.difference(marsLanding);
print(diff.inDays.abs());
print(diff.inMinutes.abs());
print(diff.inHours.abs());
}
outputs:
20049
28870560
481176
final firstDate = DateTime.now();
final secondDate = DateTime(firstDate.year, firstDate.month - 20);
final yearsDifference = firstDate.year - secondDate.year;
final monthsDifference = (firstDate.year - secondDate.year) * 12 +
firstDate.month - secondDate.month;
final totalDays = firstDate.difference(secondDate).inDays;
Simple approach, no packages needed.
try intl package with the following code:
import 'package:intl/intl.dart';
String startDate = '01/01/2021';
String endDate = '01/01/2022';
final start = DateFormat('dd/MM/yyyy').parse(startDate);
final end = DateFormat('dd/MM/yyyy').parse(endDate);
Then, you can calculate the duration between the two dates with the following code:
final duration = end.difference(start);
To obtain the number of years, months and days, you can do the following:
final years = duration.inDays / 365;
final months = duration.inDays % 365 / 30;
final days = duration.inDays % 365 % 30;
Finally, you can use these variables to display the result in the desired format:
final result = '${years.toInt()} years ${months.toInt()} months y ${days.toInt()} days';
DateTime difference in years is a specific function, like this:
static int getDateDiffInYear(DateTime dateFrom, DateTime dateTo) {
int sign = 1;
if (dateFrom.isAfter(dateTo)) {
DateTime temp = dateFrom;
dateFrom = dateTo;
dateTo = temp;
sign = -1;
}
int years = dateTo.year - dateFrom.year;
int months = dateTo.month - dateFrom.month;
if (months < 0) {
years--;
} else {
int days = dateTo.day - dateFrom.day;
if (days < 0) {
years--;
}
}
return years * sign;
}
difHour = someDateTime.difference(DateTime.now()).inHours;
difMin = (someDateTime.difference(DateTime.now()).inMinutes)-(difHour*60);
and same for years and days
in flutter we can get current month using this
var now = new DateTime.now();
var formatter = new DateFormat('MM');
String month = formatter.format(now);
But how to get the last month date? Especially if current date is January (01). we can't get the right month when we use operand minus (-) , like month - 1.
You can just use
var prevMonth = new DateTime(date.year, date.month - 1, date.day);
with
var date = new DateTime(2018, 1, 13);
you get
2017-12-13
It's usually a good idea to convert to UTC and then back to local date/time before doing date calculations to avoid issues with daylight saving and time zones.
We can calculate both first day of the month and the last day of the month:
DateTime firstDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month, 1);
DateTime lastDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month + 1).subtract(Duration(days: 1));
DateTime.utc takes in integer values as parameters: int year, int month, int day and so on.
Try this package, Jiffy, it used momentjs syntax. See below
Jiffy().subtract(months: 1);
Where Jiffy() returns date now. You can also do the following, the same result
var now = DateTime.now();
Jiffy(now).subtract(months: 1);
We can use the subtract method to get past month date.
DateTime pastMonth = DateTime.now().subtract(Duration(days: 30));
Dates are pretty hard to calculate. There is an open proposal to add support for adding years and months here https://github.com/dart-lang/sdk/issues/27245.
There is a semantic problem with adding months and years in that "a
month" and "a year" isn't a specific amount of time. Years vary by one
day, months by up to three days. Adding "one month" to the 30th of
January is ambiguous. We can do it, we just have to pick some
arbitrary day between the 27th of February and the 2nd of March.
That's why we haven't added month and year to Duration - they do not
describe durations.
You can use the below code to add months in a arbitrary fashion (I presume its not completely accurate. Taken from the issue)
const _daysInMonth = const [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
bool isLeapYear(int value) =>
value % 400 == 0 || (value % 4 == 0 && value % 100 != 0);
int daysInMonth(int year, int month) {
var result = _daysInMonth[month];
if (month == 2 && isLeapYear(year)) result++;
return result;
}
DateTime addMonths(DateTime dt, int value) {
var r = value % 12;
var q = (value - r) ~/ 12;
var newYear = dt.year + q;
var newMonth = dt.month + r;
if (newMonth > 12) {
newYear++;
newMonth -= 12;
}
var newDay = min(dt.day, daysInMonth(newYear, newMonth));
if (dt.isUtc) {
return new DateTime.utc(
newYear,
newMonth,
newDay,
dt.hour,
dt.minute,
dt.second,
dt.millisecond,
dt.microsecond);
} else {
return new DateTime(
newYear,
newMonth,
newDay,
dt.hour,
dt.minute,
dt.second,
dt.millisecond,
dt.microsecond);
}
}
To get a set starting point at the start of a month, you can use DateTime along with the Jiffy package.
DateTime firstOfPreviousMonth
= DateTime.parse(
Jiffy().startOf(Units.MONTH)
.subtract(months: 1)
.format('yyyy-MM-dd'). //--> Jan 1 '2021-01-01 00:00:00.000'
);
var fifthOfMonth
= firstOfPreviousMonth.add(Duration(days: 4)); //--> Jan 5 '2021-01-05 00:00:00.000'
or
DateTime endOfPreviousMonth
= DateTime.parse(
Jiffy().endOf(Units.MONTH)
.subtract(months: 2)
.format('yyyy-MM-dd'). //--> Dec 30 '2020-12-31 00:00:00.000'
// endOf always goes to 30th
);
var previousMonth
= endOfPreviousMonth.add(Duration(days: 2)); //--> Jan 1 '2021-01-01 00:00:00.000'
DateFormat('MMMM yyyy')
.format(DateTime(DateTime.now().year, DateTime.now().month - 2)),
List<DateTime> newList = [];
DateFormat format = DateFormat("yyyy-MM-dd");
for (var i = 0; i < recents.length; i++) {
newList.add(format.parse(recents[i]['date'].toString()));
}
newList.sort(((a, b) => a.compareTo(b)));
var total = 0;
for (var i = 0; i < newList.length; i++) {
if (DateTime.now().difference(newList[i]).inDays < 30) {
print(newList[i]);
total++;
}
}
print(total);
You can use this to fetch the last 30 days.
In addition to Günter Zöchbauer Answer
var now = new DateTime.now();
String g = ('${now.year}/ ${now.month}/ ${now.day}');
print(g);
Trying to add 1 day to the simple date format.
import java.text.SimpleDateFormat
Date date = new Date();
def dateformat = new SimpleDateFormat("YYYY-MM-dd")
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
Date date1 = (Date)dateformat.parse(currentDate);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
log info c1.add(Calendar.Date,1);
Error occurred in line :
"log info c1.add(Calendar.Date,1);"
groovy.lang.MissingPropertyException:No such property: info for class: Script16 error at line: 10
Note : The current date should be any date in future and i want to increment by 1 day.
You can use TimeCategory to add the day as shown below:
use(groovy.time.TimeCategory) {
def tomorrow = new Date() + 1.day
log.info tomorrow.format('yyyy-MM-dd')
}
EDIT: based on OP comments
Here is another away which is to add method dynamically, say nextDay() to Date class.
//Define the date format expected
def dateFormat = 'yyyy-MM-dd'
Date.metaClass.nextDay = {
use(groovy.time.TimeCategory) {
def nDay = delegate + 1.day
nDay.format(dateFormat)
}
}
//For any date
def dateString = '2017-12-14'
def date = Date.parse(dateFormat, dateString)
log.info date.nextDay()
//For current date
def date2 = new Date()
log.info date2.nextDay()
You may quickly the same online demo
Well, the error you provide clearly tells you, that you have a syntax error. It says that there is no property info.
This is because you write
log info c1.add(Calendar.Date,1);
instead of
log.info c1.add(Calendar.Date,1);
If you would have used the correct syntax, it would complain that Calendar has no property Date.
So instead of
c1.add(Calendar.Date, 1)
you meant
c1.add(Calendar.DAY_OF_MONTH, 1)
But in Groovy you can even make it easier, using
c1 = c1.next()
Is it possible to parse a date and extract the week of month using Joda-Time. I know it is possible to do it for the week of year but I cannot find how/if it is possible to extract the week of month.
Example: 2014-06_03 where 03 is the third week of this month
DateTime dt = new DateTime();
String yearMonthWeekOfMonth = dt.toString("<PATTERN for the week of month>");
I have tried the pattern "yyyyMMW" but it is not accepted.
Current joda-time version doesn't support week of month, so you should use some workaround.
1) For example, you can use next method:
static DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM_'%d'");
static String printDate(DateTime date)
{
final String baseFormat = FORMATTER.print(date); // 2014-06_%d
final int weekOfMonth = date.getDayOfMonth() % 7;
return String.format(baseFormat, weekOfMonth);
}
Usage:
DateTime dt = new DateTime();
String dateAsString = printDate(dt);
2) You can use Java 8, because Java's API supports week of month field.
java.time.LocalDateTime date = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM_W");
System.out.println(formatter.format(date));
This option in Joda is probably nicer:
Weeks.weeksBetween(date, date.withDayOfMonth(1)).getWeeks() + 1
For the case you don't like calculations so much:
DateTime date = new DateTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date.toDate());
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
If the start day of week is Monday then you can use it:
public int getWeekOfMonth(DateTime date){
DateTime.Property dayOfWeeks = date.dayOfWeek();
return (int) (Math.ceil((date.dayOfMonth().get() - dayOfWeeks.get()) / 7.0)) + 1;
}