回声日期2015年12月

I am using below jQuery:

$rezultat = "SELECT sum(vrednost) as vrednost FROM vrednosti WHERE username = '$username' AND cas between '".date("Y-".(date("m")-1)."-01")."' AND '".date("Y-".(date("m")-1)."-31 23:59:59")."' ";

This works fine, where previous month is in the same year as current date.

But now I run into trouble, because can't echo december, which is different year (2015) than january (2016).

Is there any elegant solution?

You can use strtotime function to get previous month date, pass that time value to date function as second argument like date("Y-m-d", strtotime("today -1 month")), also to get the last date of any month by changing the date format in date function argument, e.g. to get last date of previous month you can use date("Y-m-t", strtotime("today -1 month")).

So, in your case, try this:

$rezultat = "SELECT sum(vrednost) as vrednost FROM vrednosti WHERE username = '$username' AND cas between '". date("Y-m-01", strtotime("today -1 month")) ."' AND '".date("Y-m-t", strtotime("today -1 month")) ."' ";
$rezultat = "SELECT sum(vrednost) as vrednost FROM vrednosti WHERE username = '$username' AND cas between '".date("Y-m-01", mktime(23, 59, 59, date("n")-1, date("j"), date("Y")))."' ";