How i can get default date if more than 6 hours have passed? - momentjs

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 }
}

Related

How to use for loop to create multiple dates?

I have a function here that gets the date, and adds one week to it:
func thingy() {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
print(futureDate!.formatted())
}
This gets the current date, adds one week to it, and prints out that date.
I want to get a for loop that will give the date, for example maybe 10 weeks in the future, maybe looking something like this:
for i in 1...num[ex: 11] {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
let match = (title: "Test", date: futureDate)
}
I get this error:
Referencing operator function '*' on 'DurationProtocol' requires that 'DateComponents' conform to 'DurationProtocol'
How do I fix this?
I would advise adding .weekOfYear to the date. E.g., to get an array of Date representing the next ten weeks:
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dates = (1 ... 10)
.compactMap { calendar.date(byAdding: .weekOfYear, value: $0, to: today) }

Difference Between Two localDate

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.

Get Last Month Date In Flutter / Dart

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);

Countdown to a date. Swift 3 and Firebase

I'm wanting to use my Firebase database that has the values of a product i.e. lifespan (an integer not a date) and use it to compare the date in which the user has added the item i.e. 25/03/17, I'm not sure how to achieve this. Can somebody give me some advice. I believe it is to do with approximation, so if the liespan is equal 7 then the user should see 7 days and it would decrease each day, so basically a countdown. I've looked at NSDate documentation and the SwiftDate framework and do have a bit of knowledge on the methods I might need to use.
I have this example where it gets the engagement date and compares it with the wedding date, I'm thinking this is somewhat similar to what I want to try and achieve. However as this uses two dates and I want to use a date and an integer:
formatter.dateFormat = "dd/MM/yyyy"
let dateArray = message["message"] as! NSMutableArray
if let startTimeString = dateArray[0] as? String {
let weddingDate = formatter.dateFromString(startTimeString)
var engagementDate:NSDate? = nil
if let endTimeString = dateArray[1] as? String {
engagementDate = formatter.dateFromString(endTimeString)
}
let now = NSDate()
let totalEngagementTime = userCalender.components(.Day, fromDate: engagementDate!, toDate: weddingDate!, options: []).day
let daysFromEngagementUntilNow = userCalender.components(.Day, fromDate: engagementDate!, toDate: now, options: []).day
let percentage = (Double(daysFromEngagementUntilNow) / Double(totalEngagementTime)) * 100.00
let timeUntilWedding = userCalender.components(requestedComponent, fromDate: now, toDate: weddingDate!, options: [])
Hope I made sense, thank you in advance! :)
In response to a comment from the OP, this answers the question how to calculate
time between two dates
as well as perform a query on Firebase to retrieve events between now and a future date.
Given a Firebase structure to track events:
events
event_0
datestamp: "20170405"
event_name: "A concert"
event_1
datestamp: "20170501"
event_name: "Wine tasting"
event_2
datestamp: "20170410"
event_name: "50th birthday"
Assuming today is 20170402 (April 2nd, 2017) and we want all of the events for the next 30 days along with how many days until the event, when we run the following code and query:
let minuteInterval:TimeInterval = 60.0 //how to work with TimeIntervals
let hourInterval:TimeInterval = 60.0 * minuteInterval
let dayInterval:TimeInterval = 24 * hourInterval
let sevenDaysInterval = dayInterval * 30 //30 days from now
let today = Date() //today
var futureDate = Date()
futureDate.addTimeInterval(sevenDaysInterval) //future date is seven days from now
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd" //format the date to match how it's stored in Firebase
let startString = formatter.string(from: today)
let endString = formatter.string(from: futureDate)
let eventsRef = self.ref.child("events")
let myQuery = eventsRef.queryOrdered(byChild: "datestamp")
.queryStarting(atValue: startString)
.queryEnding(atValue: endString)
myQuery.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! FIRDataSnapshot
let dict = snap.value as! [String: Any]
let eventName = dict["event_name"] as! String
let eventDateStampString = dict["datestamp"] as! String
let endDate = formatter.date(from: eventDateStampString)
let daysUntilEvent = self.daysDiff(startDate: today, endDate: endDate!)
print("event: \(eventName) days from now: \(daysUntilEvent)")
}
})
and a little function do to the difference in dates calculation
func daysDiff(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let date1 = calendar.startOfDay(for: startDate)
let date2 = calendar.startOfDay(for: endDate)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
and the result is
event: A concert days from now: 3
event: 50th birthday days from now: 8
event: Wine tasting days from now: 29

Best Way To Get All Dates Between DateA and DateB

I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS
DateTime startDate;
DateTime endDate;
DateTime currentDate = startDate;
List<DateTime> dates = new List<DateTime> ();
while (true)
{
dates.Add (currentDate);
if (currentDate.Equals (endDate)) break;
currentDate = currentDate.AddDays (1);
}
It assumes that startDate < than endDate, you get the results on the "dates" list
IEnumerable<DateTime> RangeDays(DateTime RangeStart, DateTime RangeEnd) {
DateTime EndDate = RangeEnd.Date;
for (DateTime WorkDate = RangeStart.Date; WorkDate <= EndDate; WorkDate = WorkDate.AddDays(1)) {
yield return WorkDate;
}
yield break;
}
Untested code... but should work.
I voted up AlbertEin because he gave a good answer, but do you really need a collection to hold all the dates? When you are rendering the day, couldn't you just check if the date is withing the specified range, and then render it differently, no need for a collection. Here's some code to demonstrate
DateTime RangeStartDate,RangeEndDate; //Init as necessary
DateTime CalendarStartDate,CalendarEndDate; //Init as necessary
DateTime CurrentDate = CalendarStartDate;
String CSSClass;
while (CurrentDate != CalendarEndDate)
{
if(CurrentDate >= RangeStartDate && CurrentDate <= RangeEndDate)
{
CSSClass= "InRange";
}
else
{
CSSClass = "OutOfRange";
}
//Code For rendering calendar goes here
currentDate = currentDate.AddDays (1);
}
// inclusive
var allDates = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(i => startDate.AddDays(i));
// exclusive
var allDates = Enumerable.Range(1, (endDate - startDate).Days).Select(i => startDate.AddDays(i));

Resources