Im trying to multiply “hours” with “pay” rate to give “total pay” in currency i.e. sterling. My code is
#IBAction func totalpay (sender : AnyObject) {
let num1 = Double(pay.text!) ?? 00
let num2 = Double(hours.text!) ?? 00
let description = num1 * num2
totalpayLabel.text! = String(format: "%.2f", (description))
}
All “hours” are NSDate and “pay” is String
You are getting 0.0 because one of the values pay.text or hours.text is not getting converted to numbers , I guess maybe you are not able to get the hours from NSDate correctly as a number . If you want to get current hour you can straight away get it with this code . let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
.First try to print the values of hours.text and pay.text and you will know what I'm saying
Related
Using Vue js and v-validate how can I determine if the date of birth is greater than 21 and less then 55 years old? Any help is greatly appreciated.
import * as moment from "moment";
let birthday = moment(moment.now()).diff(moment(this.user.day + this.user.month + this.user.year, "DD.MM.YYYY"),"years");
if(birthday > 21 && birthday < 55) {
// do next steps
}
Moment(npm install moment) is used to parse, manipulate & display dates and times in JavaScript. moment.now() will give the present date and assuming you have three fields for day, month and year in different variables, format it and use the diff function to find the age.
The example from Madhuri works for me but i change the input as hard coded string.
enter code here let birthday = moment(moment.now()).diff(moment('01.01.1990', "DD.MM.YYYY"), "years");
if(birthday >= 20 && birthday <=70 ){
return birthday;
}
}
I solved it with with value from form input which works for me.
checkBirthday(){
const birthDayDate = document.getElementById("birthdate").value;
const age = moment().diff(birthDayDate, "years");
// let birthday = moment(moment.now()).diff(moment('01.01.1990', "DD.MM.YYYY"), "years");
if(age >= 18 && age <=74 ){
return age;
}
},
When I load a page with a Time object and echo it out on the page through PHP, I get this:
<?= $user->last_login ?>
// 12/30/14, 5:21 pm
When I load data through ajax, it's returned to me like this:
console.log(response.user.last_login);
// 2014-12-30T17:21:31+0000
I haven't set anything different from the default CakePHP 3 setup, and I need events that are added to the page (returned via ajax) to be in the same time format as events that were pulled on page load (return via PHP).
The default output in string format for Time objects is controlled by the setToStringFormat method http://book.cakephp.org/3.0/en/core-libraries/time.html#setting-the-default-locale-and-format-string
It is a good practice to not hardcode a format there, but to only change the current locale so that the right format is selected for you,
But the format that is used to encode to json is not possible to control it via configuration as it is a standard that dates should be presented in such format when encoded in a JSON API. Instead, what you can do is alter the jsonSerialize method in your User entity:
public function jsonSerialize() {
$toEncode = parent::jsonSerialize();
return ['last_login' => (string)$this->last_login] + $toEncode;
}
What it does is converting to string the last_login property before it is encoded to json. Converting to string will then use the globally configured toString format.
You can convert the format of the date using the javascript Date object
JSFiddle
var date = new Date(response.user.last_login)
//returns a timestamp of 1419960091000
var n = date.getTime();
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
//increment the month by 1 as it starts from 0
var year = date.getFullYear();
year = year.toString().substr(2,2);
//this removes the first 2 characters to give yy, remove the above line for yyyy
var hours = date.getHours();
var minutes = date.getUTCMinutes();
var period='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12){
hours=hours%12;
//remove the above line for 24 hour format
period='pm';
}
Now you can piece together the date in the required format
var last_login = day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ' ' + period;
//gives 30/12/14 5:21 pm
Hope this helps!
I want to calculate the number of days in asp.net by AJAX calender extender on text box. But i am not getting the right output which i want. I can't find the error which is coming in output. The code is
string a = TextBox1.Text;
string b = TextBox2.Text;
DateTime t1 = Convert.ToDateTime(a);
DateTime t2 = Convert.ToDateTime(b);
TimeSpan days = t2 - t1;
int zile = Convert.ToInt32(Math.Ceiling(365-(days.TotalDays)));
TextBox3.Text = zile.ToString();
I am not getting the right output.
As I see, you are calculating the days difference in the code behind file. You can calculate it easily like below.
TimeSpan diff = Convert.ToDateTime(TextBox2.Text).Subtract(Convert.ToDateTime(TextBox1.Text));
int noOfDays = diff.Days + 1;
Maybe a fresh set of eyes can help. I have been at it for hours trying different things and this was the only one that had a close result to what i want.
Table:
The Price Field is set as money with values like 3.99,4.99,17.99
Code:
var totalprice = (int)db.QueryValue(#"SELECT SUM(CoverPrice) FROM Comics WHERE Approved='1' AND ArcId = #0", aId);
Call it with:
#String.Format("{0:c}", totalprice)
Which outputs:
$26
But I want it to print out with the decimal and the 2 numbers after it which should be 26.97. What did I miss???
This happens because you cast your totalprice variable to an int.
Change
var totalprice = (int)db.QueryValue(#"SELECT SUM(CoverPrice) FROM Comics WHERE Approved='1' AND ArcId = #0", aId);
to
var totalprice = (decimal)db.QueryValue(#"SELECT SUM(CoverPrice) FROM Comics WHERE Approved='1' AND ArcId = #0", aId);
When you cast the amount as int, you lost the cents, you need to cast it as decimal:
var totalprice = (decimal)db.QueryValue(#"SELECT SUM(CoverPrice) FROM Comics WHERE Approved='1' AND ArcId = #0", aId);
We have a database of swimmers with their times.
To create a ranking we want to get the fastest time of each athlete.
var rankings = (
from r in _db.Results
orderby r.swimtime
group r by r.athleteid into rg
select new
{
AthleteId = rg.Key,
FirstName = rg.Min(f2 => f2.Athlete.firstname),
Swimtime = rg.Min(f8 => f8.swimtime),
hours = rg.Min(f9 => f9.swimtime.Hours),
minutes = rg.Min(f10 => ("00" + f10.swimtime.Minutes.ToString()).Substring(("00" + f10.swimtime.Minutes.ToString()).Length - 2)), // to get 2 digits in minutes
seconds = rg.Min(f11 => ("00" + f11.swimtime.Seconds.ToString()).Substring(("00" + f11.swimtime.Seconds.ToString()).Length - 2)), // to get 2 digits in seconds
milliseconds = rg.Min(f12 => (f12.swimtime.Milliseconds.ToString() + "00").Substring(0, 2)), // because miliseconds are not always filled
}
);
Now the ranking is created correctly, however the time shown is not.
I know what the problem is, but don't know how to fix it:
In the database we have a swimmer that has 2 times : 00:01:02:10 (1min2sec10) and 00:00:56:95 (56sec95)
The result we get is the minimum for the minutes (=00), the minimum for the seconds (=02) and the minimum for the milliseconds (=10)
Resulting in a time of 00:00:02:10.
What we should get is the hours,minutes,seconds and milliseconds of the fastest time (=00:00:56:95)
Anyone any ideas on how to fix this ?
This should do the trick:
from result in db.Results
group result by result.AthleteId into g
let bestResult = (
from athleteResult in g
orderby athleteResult.SwimTime
select athleteResult).First()
orderby bestResult.SwimTime
select new
{
AthleteId = bestResult.Athlete.Id,
FirstName = bestResult.Athlete.FirstName,
BestTime = bestResult.SwimTime,
}
The query fetches the best result from a group (all results from a single athelete), orders by that result, and uses that result to populate the final result.
Stay away from calling .First on groups, as that can cause automatic requerying due to the difference between LINQ's group (key and elements) vs SQL's group (key and aggregates).
Instead, get the minSwimTime once and let it be.
var rankings =
from r in _db.Results
group r by r.athleteid into rg
let minSwimTime = rg.Min(x => x.swimtime)
select new
{
AthleteId = rg.Key,
FirstName = rg.Min(f2 => f2.Athlete.firstname),
Swimtime = minSwimTime,
hours = minSwimTime.Hours,
minutes = ("00" + minSwimTime.Minutes.ToString()).Substring(("00" + minSwimTime.Minutes.ToString()).Length - 2), // to get 2 digits in minutes
seconds = ("00" + minSwimTime.Seconds.ToString()).Substring(("00" + minSwimTime.Seconds.ToString()).Length - 2), // to get 2 digits in seconds
milliseconds = minSwimTime.Milliseconds.ToString() + "00").Substring(0, 2), // because miliseconds are not always filled
};
Also - don't do string formatting in the database. Database servers have better things to do than turn datetimes into text.