Calculate the difference between datepicker date and current date in Swift2 - nsdate

Hy Guys.
I'm learning swift2..
I have a datepicker element that the user enters a date. I want to calculate the difference in days, hours, minutes from the current date
I can get the date to a variable but I cannot make the difference with the current NSDate().
Any help will be appreciated.
class ViewController: UIViewController {
#IBOutlet var hourLabel: UILabel!
#IBOutlet var dobPicker: UIDatePicker!
#IBAction func convertAge(sender: AnyObject) {
let userDOB = dobPicker.date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MMMM-yyyy"
hourLabel.text = "\(dateFormatter.stringFromDate(userDOB))"
}
override func viewDidLoad() {
super.viewDidLoad()
let nowDate = NSDate()
let df = NSDateFormatter()
df.dateFormat = "dd-MMMM-yyyy"
}
}

I first calculate the difference in seconds.
let currentDate = NSDate()
let someDateInThePast = NSDate().dateByAddingTimeInterval(-100000)
let difference = currentDate.timeIntervalSince1970 - someDateInThePast.timeIntervalSince1970
For the individual amount (ex. 3 days, 92 hours, 5520 minutes)
var days = floor(difference/24/3600)
var hours = floor(difference/3600)
var minutes = floor(difference/60)
For the total amount (ex. 3 days, 20 hours, 12 minutes)
var days = floor(difference/24/3600)
var hours = floor((difference % (24*3600) ) / 3600)
var minutes = floor((difference % 3600) / 60)
var seconds = floor(difference % 60)

Related

Is there any way to display time format with am/pm in mongodb

time :
{ $dateToString: { format: "%H:%M:%S:%L%z", date: "$generated_on", timezone: "+05:30" }}
with the help of this time is generated but I want time in AM/PM format}\
So basically, for time being (version 5), Mongo DB does not support the AM/PM format on the date object, you have two options:
option one: Store the correct format in the first place
option two(heavy operation): store a JS function inside the MongoDB for this custom format and call that in your aggregation pipeline, js function would be like this:
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
Add MongoDB custom JS function myCustomDate:
db.system.js.insertOne(
{
_id: "myCustomDate",
value: function (date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
}
);
and use this based on your requirements on mapReduce command

math.ceil groovy script return value

I am trying to generate a random date between two dates, could you check the below code?
What i notice is the output as : 02.0/01.0/1918.0
How can i save it as 02/02/1918 instead of 02.0/01.0/1918.0
var dob;
//set a range of years
var min = 1900;
var max = 2004;
// Math.ceil prevents the value from being 0;
var month = Math.ceil(Math.random() * 12);
var day = Math.ceil(Math.random() * 28);
var year = Math.floor(Math.random() * (max - min) + min);
//this ensures that the format will stay mm/dd/yyyy;
if(month < 10) {
month = "0" + month;
}
if(day < 10) {
day = "0" + day;
}
//concatenates random dob in mm/dd/yyyy format;
dob = month + "/" + day + "/" + year;
return dob;
Math.floor returns double. You have to convert it to int.
var year = Math.floor(...) as int

I am trying to get the time difference between the execution of 2 commands, one is !on and the other !off (Discord.JS))

I have the following code. It works to an extent, but when I do the !off command, it shows me a 0 instead of the actual time difference.
Index Code
global.time = getDateTime()
global.oldTime = getNewDateTime().getTime
global.finalTime = parseFloat(time) - parseFloat(oldTime)
function getDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
return hour + ":" + min;
}``
console.log(parseFloat(getDateTime))
function getNewDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
return hour + ":" + min;
}
And here is the off command, same with on almost
exports.run = async (client, message, args, tools) => {
const embed = new Discord.MessageEmbed()
.setColor("BLUE")
.addField("Timer ended. Total Time Online", `**: ${finalTime}**`)
message.channel.send(embed);
}

Generating bulk dates

I wanted to ask if anyone knows a way of generating bulk dates. I want to know about how can I generate all of the dates and times between 20130631_0000 till 20151231_2359
The month limit is 0-12
The day limit is 0-31
and the part you see after underscore is hour and minute, the hour limit is 00 till 23 and the minute is from 00 till 59. It's basically YYYYMMDD_HHMM
Few examples:
20130810_1154, 20140103_2357, 20150722_1049, 20140103_2358, 20140103_2359, 20140104_0000, 20140104_0001, 20140105_1159, 20140105_1200
If you simply want to print each date to the console:
let date = new Date(2013,6,31,0,0);
const endDate = new Date(2015,12,31,23,59);
const padWithZero = num => num.toString().padStart(2, '0');
while (date <= endDate) {
const year = date.getFullYear();
const month = padWithZero(date.getMonth()+1);
const day = padWithZero(date.getDate());
const hour = padWithZero(date.getHours());
const minute = padWithZero(date.getMinutes());
console.log(`${year}${month}${day}_${hour}${minute}`)
date = new Date(date.getTime() + 60000)
}
Try this
function convertStringToDate(date){
var year = date.substring(0,4)
var month = date.substring(4,6)
var day = date.substring(6,8)
var hour = date.substring(9,11)
var minute = date.substring(11,13)
return new Date(parseInt(year), parseInt(month), parseInt(day), parseInt(hour), parseInt(minute) )
}
function addMinute(date){
var new_date = date;
new_date.setMinutes(date.getMinutes()+1)
return new_date
}
function getDatesBetween(start_date_str, end_date_str){
var start_date = convertStringToDate(start_date_str)
var end_date = convertStringToDate(end_date_str)
dates = []
date = start_date
while(date.getTime() !== end_date.getTime()){
dates.push(new Date(date))
date = addMinute(date)
}
dates.push(end_date)
return dates
}
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
function convertDateToString(date){
var year = date.getFullYear().toString()
var month = pad(date.getMonth().toString(),2)
var day = pad(date.getDay().toString(),2)
var hour = pad(date.getHours().toString(),2)
var minutes = pad(date.getMinutes().toString(),2)
return year + month + day + "_" + hour + minutes
}
var start_date_str = "20130620_1224"
var end_date_str = "20130621 1224"
dates = getDatesBetween(start_date_str, end_date_str)
formatted_dates = dates.map(convertDateToString)
console.log(dates.length)
console.log(dates[dates.length-1])
console.log(formatted_dates.length)
console.log(formatted_dates[dates.length-1])

Individual start date per month

together
how do I get it in PowerPivot or as Dax formula out that for my internal / individual months the beginning of the month from 31.120.2018 for January 2019 receive?
So, that I get the January in the PowerPivot calendar table already from 31.12.2018 and then in the 4-4-5 weeks cycle?
So
31.12.2018 + 28 days = January
31.12.2018 + (28 days * 2) = February
31.12.2018 + (28 days * 2) + 7 days = March
Does anyone have an idea?
Best Regards
First I create a calendar table, this is the simple part, I took a random start and end for testing:
CalendarDates = CALENDAR(DATE(2012;12;20);DATE(2021;1;5))
Then I added the column WeekNumber, this is to the greorgian calendar. A bit complicated because microsoft simply starts counting with 1 on the first of january..
WeekNumber =
var wNrfirstDayJanNextYear = WEEKNUM(DATE(CalendarDates[Date].[Year] + 1;1;1);2)
var fullWeekNextYear = WEEKNUM(DATE(CalendarDates[Date].[Year] + 1;1;7);2) = 1 //If day 7 of week is still first week, its a full week
var wNr31Dex = WEEKNUM(DATE(CalendarDates[Date].[Year];12;31);2)
var wNr31DexPrevYear = WEEKNUM(DATE(CalendarDates[Date].[Year]-1;12;31);2)
var wNr = WEEKNUM(CalendarDates[Date];2)
var pbi4JanWeekNrNextYear = WEEKNUM(DATE(CalendarDates[Date].[Year] + 1;1;4);2)
var pbi4JanWeekNr = WEEKNUM(DATE(CalendarDates[Date].[Year];1;4);2)
var wNrComp = if (pbi4JanWeekNr =2; wNr - 1; wNr)
return if(NOT(fullWeekNextYear) && wNr = wNr31Dex;IF(pbi4JanWeekNrNextYear = 2; wNr31Dex;1);if(wNrComp = 0; wNr31DexPrevYear; wNrComp))
last step is to create the Month based on the week number:
Month =
var quater = FLOOR((CalendarDates[WeekNumber] - 1)/13; 1)
var quarterWeek = MOD(CalendarDates[WeekNumber] - 1 - (quater*13);13)
var monthNr = FLOOR(quarterWeek/4;1)
var month445 = if (monthNr = 3; 2; monthNr) + quater * 3 + 1
return if (month445 = 13; 12;month445)
Note: I corrected week 53 in the last quarter so it becomes 4-4-6. You need to do your own math if you want it different.
End result:

Resources