Using Node.js (Express) and mySQL to INSERT for a TIMESTAMP? - mysql

Just trying to do some simple messaging here:
var post = {
sender_username : sender_username,
recipient_username : recipient_username,
message_no : 1,
content : content,
time : ***CURRENT TIMESTAMP***,
read : 0
};
connection.query('INSERT INTO message SET ?', post, function(err, result) {
if (err) {
res.send(err);
}
else {
res.send(post);
}
});
What's the simplest way to stick the date and time in there that is valid for the TIMESTAMP type?

You can use Moment.js for this purpose:
Date.now returns current timestamp in millisecond and moment also works with milliseconds.
var mysqlTimestamp = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');

The native JS way can be found in the answers here.
Personally, I use Moment.js for anything that deals with dates.
moment().utc().format('hh:mm:ss')
NOTE: I got confused with your question. You asked for "CURRENT_TIME" but your format is TIMESTAMP. MySQL's TIME and TIMESTAMP types are different. TIMESTAMP contains both the date and time and the default value function for that is "CURRENT_TIMESTAMP". I'm assuming you're referring to the TIME type.

You can use {time: new Date(GMTtimeString).toLocaleString()} where GMTtimeString sent from front-end.

Related

Working with date time in web api

I have created a WEB APIusing MySQL database. The table includes the data about the meter's serial numbers it's signal strength values and the date time on which the signal strength has comes. For now i am successful in getting data by sending the meter's serial number.
Now I am also sending the date time parameter to it also. But it's not working for me. Below is what i have done.
public HttpResponseMessage GetByMsn(string msn, DateTime dt)
{
try
{
return Request.CreateResponse(HttpStatusCode.Found, medEntitites.tj_xhqd.Where(m=> m.msn == msn).Where(a=> a.date_time < dt ));
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
The WebApiConfig file includes
config.Routes.MapHttpRoute(
name: "GetByMsn",
routeTemplate: "api/{controller}/{action}/{msn}/{dt}",
defaults: null,
constraints: new { msn = #"^[0-9]+$" , dt = #"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$" }
);
After that I am passing the URL like http://localhost:14909/api/meters/GetByMsn/000029000033/2017-10-06T07:52:27
The error I am getting is A potentially dangerous Request.Path value was detected from the client (:).
For this I have also searched for the solutions but couldn't find out the correct one. Also I have replaced : in date time but still it's not working for me
Update 1
While passing only date2017-10-06 it works for me but when I append it with time it doesn't works
For a quick check I checked this question but still i am unable to solve the solution.
I must be missing something that I don't know
Any help would be highly appreciated.
After a lot of searching I finally found a solution.
I have changed the predefined disallowed/invalid characters in my Web.config. Under , added the following: <httpRuntime requestPathInvalidCharacters="<,>,%,&,*,\,?" />. I've removed the : from the standard list of invalid characters.
For more information see this solution

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.

How do you get a timestamp in ClojureScript?

How can I get a timestamp in ClojureScript, similar to Unix's timestamp, a single number that represents the current time and date, as a number. I know that:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
can be used in Javascript but I want to know if there is a ClojureScript equivalant
You can use
(.getTime (js/Date.))
or you could also use now or epoch from cljs-time.
The most efficient way is this
(.now js/Date)
Other answers needlessly create a Date object.

Sequelize query with dates

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
});

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.