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
Related
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) }
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 have to find the difference between two times in 24 hour format. I have the two time strings, Eg: 10:40 and 18:20. How can I find the difference between these two times in Flutter?
You can use intl package.
var format = DateFormat("HH:mm");
var one = format.parse("10:40");
var two = format.parse("18:20");
print("${two.difference(one)}"); // prints 7:40
A complete answer for perfect calculation is given bellow
String start_time = formateTime('12:00'); // or if '24:00'
String end_time = formateTime('24:00'); // or if '12:00
var format = DateFormat("HH:mm");
var start = format.parse(start_time);
var end = format.parse(end_time);
if (start.isAfter(end)) {
print('start is big');
print('difference = ${start.difference(end)}');
} else if(start.isBefore(end)){
print('end is big');
print('difference = ${end.difference(start)}');
}else{
print('difference = ${end.difference(start)}');
}
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()
I've this code that changes the maximum date of a second Calendar Extender to 90 days after the date that has been defined in a first one and minimum to the same it has been selected on the first and it works right except for one thing.
var cal2 = $find("calendar2");
var fecha = cal._selectedDate;
var date = fecha.getDate() + 90;
var year = fecha.getFullYear();
var month = fecha.getMonth();
var todayDate = new Date(year, month, date);
cal2._startDate = cal._selectedDate;
cal2._selectedDate = fecha;
cal2._switchMonth(fecha);
cal2._endDate = todayDate;
Problem is that if I first seelct a date on cal, dates are properly shown in cal2, but I select one on cal again then cal2 doesn't display in the same month that cal, what's much worse it displays to select days that would be now impossible to select and in fact you can select them unless you go back first to month mode.
Any idea on how to "refresh" the behavior of the second CalendarExtender?
Thank you.
you can use this method.
Sys.Extended.UI.CalendarBehavior.prototype.refresh = function () {
this._isOpen = true;
this._ensureCalendar();
this.invalidate();
this._isOpen = false;
}
When you add the method only call:
cal2.refresh()