Sequelize query with dates - mysql

I'd like to make a query on dates using SequelizeJS but i don't know how to do and there is nothing on that on the website...
My code :
var day = request.params.day;
Appointment.findAll({where: ["start.day() = day"]}); // start is my column, format with DATETIME

Depending on your DB there might be some function to extract the day from the column. Never seen the .day syntax before though.
Appointment.findAll({
where: sequelize.where(sequelize.fn('day', sequelize.col('start')), day)
});
On latest master this should produce something like
WHERE DAY("start") = day

You can just use the regular comparison operator, as long as your date is in a valid format. For this purpose you can just create a Date object out of the input, and then pass it to the Sequelize query, like this:
var day = new Date(request.params.day);
Appointment.findAll({where: ['start > ?', day]}).then(function (result) {
// do stuff here
});

Related

Set future expiry date as default value in sequelize

I'm saving logintokens with a lifetime of 365 days using the following sequelize beforeCreate Hook:
let hooks = {
setExpires: (instance, options, done) => {
if(instance.get('expires')) {
return done();
}
instance.set('expires', Sequelize.literal('NOW() + INTERVAL 1 YEAR'));
return done();
}
};
Logintoken.beforeCreate(hooks.setExpires);
Logintoken.beforeBulkCreate(hooks.setExpires);
It works great as long as I use MySQL. Other dialects such as SQLite don't understand NOW() + INTERVAL 1 YEAR, which is bad. Is there a built-in cross-dialect way to achieve what I am trying to do here?
I've already studied the docs, googled like hell and even had a look at the source code but couldn't find anything that looks like date calculation.

ZF2 Query WHERE clause with DATE() for datetime column

I have a column with datetime data type and I want to build a SQL query in Zend Framework2 which compare date part with user input date.
Need to build similar part as DATE(datetime column) = '2014-09-16' with;
$select->where();
would be very grateful if someone could help on this.
Use like this:
$date = '2014.05.24';
$select->where('date(expecting_date) = "'.$date.'"');
You should use predicate expression for these kind of conditions, like :
$select = new \Zend\Db\Sql\Select(table name);
$select->where(new \Zend\Db\Sql\Predicate\Expression('DATE(datetime) = ?', '2014-09-16'));

How to take Date from sql db as a single result and compare with current date

i have a complex problem with Date field. Describe what i want to do:
I have field date1 as Date in my db.
#Temporal(TemporalType.DATE)
private Date date1;
I want to take data from this field and compare with current date.
#Query("SELECT date1 FROM Table io WHERE io.date1 >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-%e')")
Date findAll2();
public boolean CheckDate1(){
currentDate = new Date();
date1 = getInterimOrdersRepo().findAll2();
if(currentDate.before(date1) || currentDate.equals(date1)){
System.out.println("TRUE");
System.out.println("currentDate = "+currentDate);
return true;
}
else{
System.out.println("FALSE");
return false;
}
}
but i have an error:
result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException
When method return false i want do Update field data1 with " " empty data.
I using jsf, what i must to do?
It seems that you are trying to read several values from the table into a single variable, and that is the error.
findall2 returns an array (most likely) and u should read one of it's values - try reading first one.
Furthermore, I believe that you can skip the "DATE_FORMAT" in your query, and this is a very strange way to write a code. Not clear what u are trying to achieve here

Format JSON date before pushing into ko.observableArray

I am pushing Values into a ko.observalbeArray with an AJAX call,
I want to format the JSON return date to "YYYY-MM-DD" before I am pushing it into my observableArray.
The Specific element in my Code that I want to convert is: OrderTimeStamp: element.OrderTimeStamp
Here is an example of a date that gets returned from server:
/Date(1377200468203+0200)/
Here is my AJAX call:
$.ajax({
url: "/[URL TO API Method]/GetAllOrdersbyparm",
data: {Parm: ko.toJS(MyDataViewModel.SelectedParmater), Start: ko.toJS(MyDataViewModel.ParmStart), End: ko.toJS(MyDataViewModel.ParmEnd)},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
MyDataViewModel.OrderDetails.push({ OrderID: element.OrderID, OrderGUID: element.OrderGUID, OrderTimeStamp: element.OrderTimeStamp, OrderStatus: element.OrderStatus, QtyProductsOnOrder: element.QtyProductOnOrder, PaymentDate: element.PaymentDate });
}
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
So, this is an ASP.NET specific Microsoft Date "standard".
See
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
why it should be avoided like the plague(1).
In that format the first component is a UTC milliseconds offset since the UNIX epoch.
The offset is TO local time, which is the opposite of the timezone offset in the JS Date string representations.
Use
var dateString = myDate.toJSON();
to serialize a JS Date object for sending.
Such a serialized datetime string, which is also in UTC (aka *Z*ulu), can be used to create a Date object thusly:
var myDate = new Date(dateString);
(1) In case you need to support this old ASP.NET Date format you can convert it to a proper JS Date like this (thanks [Roy Tinker][2]):
myDate = new Date(parseInt("/Date(1377200468203+0200)/".substr(6)));
I'm not familiar with that particular datetime notation.
Is that home-grown?
Is there documentation for that?
If not, then you are setting yourself up for trouble trying to interpret it.
That conversion toJSON would make it a UTC time and a few things are open for interpretation, unless documented in minute (no pun intended) detail.
So this is my answer: Be very sure you have the above definition in normative writing.
Now let me ramble on for a bit:
I went through that little exercise here...
http://en.wikipedia.org/wiki/ISO_8601 would be a good standard to base datetime notation on.
Now, you already get that format from the server, which looks like a millisecond time value since the epoch ('1970-01-01T00:00:00Z'), (probably with a timezone offset already applied to it!) combined with a timezone offset string in HHMM.
That's a bit scary, since those two components don't mix well.
Evaluated as an expression 1377200468203+0200 would subtract octal! 200 milliseconds! from 1377200468203. That's clearly not what's intended.
In ISO8601 (which this notation is not) this timezone offset would be FROM UTC, so the millisecond value would already have the 2 hour, 0 minutes offset applied to it.
Now the code could of course run on a machine which is in a different timezone than the datetime given.
The very crucial question is whether this millisecond datetime value has indeed the offset FROM UTC in it.
In that case, doing
var dt = new Date(1377200468203);
would be wrong.
If it is close to a daylight savings time switch time, it would be incorrect to just subtract to offset from it.
Note, not sure if below answers your question. If not, you may be helped by this one: How to format a JSON date?
Something along these lines should work:
var yyyy = element.OrderTimeStamp.getFullYear()
var mm = element.OrderTimeStamp.getMonth();
var dd = element.OrderTimeStamp.getDate();
var x = yyyy + '-' + (mm < 10 ? '0'+mm : mm) + '-' + (dd < 10 ? '0'+dd : dd)
element.OrderTimeStamp = x;
See this fiddle for an example. For reference, the MDN page has good documenation on Dates.
If you need more advanced date and time functionality I can recommend looking at MomentJS.

How to use MySQL FORMAT with CakePHP?

I cant figure out why when I try to use FORMAT function to limit number of decimal places in the results of MySQL query it doesn't work. Here is how my code looks like:
...some other options to join tables with some conditions....
$options['fields'] = array(
'MetricSim.sim_id',
'MetricSim.metric_id',
'FORMAT(MetricSim.value,3) AS value'
);
$metrics_sims = $this->Sim->find('all', $options);
If I don't use the FORMAT function I get all of the results as expected. But when I try to use it I just don't get value field in my results (the rest of the fields are in place).
Why do you want to use FORMAT in your query? You can use a Helper to format your data in your view.
For example, in your controller class you add:
var $helpers = array('Number');
and in your view, you can format the value like:
$number->format($metric_sims['MetricSim']['value']);
(See NumberHelper class)