Timestamp in node js different from database - javascript

In database time-stamp is saved as 2015-12-05 10:53:12 but when I fetch record using mysql query it return this time-stamp like 2015-12-05T10:53:12.000Z.
Why? any issue?? please help.

In your database the timestamp is saved in binary numerical format. "2015-12-05 10:53:12" & "2015-12-05T10:53:12.000Z" are string representation of that value that you see in some application.
It's the same value and there's no issue to solve here.

To convert your Date-Object (which is represented as ISOString with "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") you have to parse it after reading from the db.
In JavaScript you can do that by simply passing the string in the constructor, e.g. var myDate = new Date("2015-12-05T10:53:12.000Z")
With a custom format you could do it like this for example:
var dateString = "2015-12-05 10:53:12";
var date = Date.parse(dateString, "yyyy-MM-dd HH:mm:ss");
In order to represent it as "Dec 16, 2015" you have to parse it afterwards:
There are some good libraries for doing this (e.g. momentjs or with angularjs - date filters)
Without that you have do manually do it somehow like this (where you pass your date object created before):
function parseDate(date) {
var months = ['JAN','FEB','MAR','APR','MAY','JUN',
'JUL','AUG','SEP','OCT','NOV','DEC'];
return months[date.getMonth()]+" "+("0" + date.getDate()).slice(-2)+", "+date.getUTCFullYear();
}

You can use MySQL's DATE_FORMAT, eg.
SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y'); -> 'Sunday October 2009'
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format

Related

How can I reverse date time to ajax date time

In javascript I have some datetime like this
Date: '2017-07-04'
I want to convert it to DateTime like ajax get result.
Expect result like this:
'/Date(1565089870830)/'
How can I make it possible?
You can use Date.parse(). This method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
var date = Date.parse('2017-07-04');
console.log(date);
The format you're trying to create is a string containing an Epoch timestamp. To create that in JS you can create a Date object from the input string and retrieve the getTime() property. Then it's just a matter of concatenating that value in to the format needed. Try this:
var date = new Date('2017-07-04');
var epoch = date.getTime();
var output = `/Date(${epoch})/`;
console.log(output);
Presumably you're working with an ASP.Net MVC site, given the date format you're trying to build. One thing to note here is that you don't need to use that format when sending DateTime values back to the server. You can send any string so long as it can be bound to a DateTime instance by the ModelBinder. As such I'd recommend using an ISO8601 format instead.

Parse JSON DateTime object to local time in JQuery by ignoring timezone

I am facing an issue while parsing JSON Date Time object using moment(of course I tried many approaches suggested in Stackoverflow but nothing worked in my case).
In my application, I'm storing a DateTime value as UTC DateTime. Now when I'm displaying I need to display it according to the browser timezone. After going through many StackOverflow questions, I used "moment.js" as below
//From server, the Date object looks like /Date(1506510057813)/
//The equivalent DateTime value stored in Database is 2017-09-27 13:00:57.813
fuction DateTimeFormatter(value)
{
if (value != undefined) {
var newValue = new Date(moment.utc(value));
//But at this line, even with just moment(value) all I am getting is DateTime which is not same as UTC time.
//I don't want any time zone to get appended all I want is just 13:00:57
var newHours = newValue.getHours() - newValue.getTimezoneOffset() / 60;
var newMinutes = (newHours + '.0').split('.')[1] * 6;
newValue.setHours(newHours);
newValue.setMinutes(newMinutes);
return moment(newValue).format(applicationTableDateFormat);
}
else
return "";
}
Please let me know what I am doing wrong or is there any other way I can display time as per browser time zone.
Once you have a UTC moment, you can convert it to local.
moment.utc(value).local().format(...)
https://momentjs.com/docs/#/manipulating/local/
But it sounds like maybe your real problem is when you store the date. If you're storing it as UTC, make sure you actually convert the local value to UTC before you store it. That way when you read it, you get a predictable value that you can safely convert to any locale.
Angularjs has its own mechanism to display formatted dates on views you just needs an absolute representation of a date and it takes care of the rest. And by absolute, I mean, a Date which is settled in a timezone whether it's utc or not, you need to know what timezone you are talking about.
The date filter
It's a filter from the core module of angularjs and it accepts:
"... either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone." (Angularjs date filter)
The problem
Angularjs need a proper date input in order to display it correctly, in your case you seem to have the milliseconds format (sort of, /Date(1506510057813)/), you could use that and extract the numeric part and input that on the pipe, or you can change the server to send the ISO 8601 date (a.k.a., yyyy-MM-ddTHH:mm:ss.sssZ).
For example:
let rawDate = '/Date(1506510057813)/';
let re = /\/Date\((\d+)\)\//g; // regex to extract number from the string date
let myDate = new Date(Number(re.exec()[1])) // extract the milliseconds
Or
let rawDate = '2017-09-27T11:00:57.813Z';
let myDate = new Date(rawDate)// and you don't need to do anything else
Either way you'd end up with something like this:
<span> {{ myDate | date }}</span>

Filter Mongo document by date in Meteor

This Meteor server code parses html and gets string like "09/03/2017" and saves it to a mongodb collection like this:
const date = ResObj.$(this).next().html().trim();
const dArr = date.split('/');
const dObj = new Date(parseInt(dArr[2]), parseInt(dArr[1]) - 1, parseInt(dArr[0]));
myCol.update({_id:'abc', {$set:{date: dObj}}});
Later I need to return the documents between and include 2 dates say 09/03/2017.
The search string is being received from the client in the formate 2017-03-09.
myCol.find({date: {$gte: start, $lte: end}})
Moment.js is also installed. How can I do this so that the output is in the formate DD/MM/YYYY? thx
What you want to do is store your date as a date object, that way you can query against it in the DB.
To do that using moment, you need to parse the string in to a moment object. This is telling moment to create a date object using the date provided and telling it what format the date is in so it knows which is the days/months etc.
const dateObj = moment(date, "DD/MM/YYYY").toDate()
You are then using the moment toDate() function to convert that in to a date object which you can store in the DB.
Save that to the DB
myCol.update({_id:'abc', { $set:{ date: dateObj }}});
Then, when you are back on the client you can format the output date using moment again
const formattedDate = moment(dateFromDB).format("DD/MM/YYYY");
Basically, you always want to store your dates in the DB as date objects, that way they can be used in querys and sorted etc. You only want to convert them back to strings using format() back on the client.

Compare ISO date without time stamp in javascript

I am querying data using OData, url looks like http://myurl.com/api/Customer?$filter=ResDate eq DateTime'2014-03-15T12:01:55.123'.
I'm getting date/time from jquery.datepicker instead of the static date and using moment.js to convert from DD-MM-YYYY to YYYY-MM-DDTHH:mm:ss in order to pass it to web service.
function convertDateToISOdate(date){
var newDate = moment(date,'DD-MM-YYYY').format('YYYY-MM-DDTHH:mm:ss');
return newDate;
}
Date returns from the function, is 2014-03-15T00:00:00.
Problem : 2014-03-15T12:01:55.123 is not equal to 2014-03-15T00:00:00, so there's no record selected.
What I want is , just to compare the date , not include time stamp.
Note : I can not change the format date/time at server side(Web service) because it's not belongs to me.
Any idea is much appreciated.
Your first call to moment(date,'DD-M-YYYY') is stripping the time information from the incoming data. try using moment(date) (no format) instead because momentjs recognizes your incoming date format intrinsically, without having to be told which format to use, and will correctly parse the H:M:S data, too.
MomentJS date parse information

Passing datetime with http request

I need to pass a date time (in 2012-09-23 21:00:00 format generated by dropdown boxes and converted to that format with javascript (client side that is)) with GET method to a php file which then gets mysql records sorted by that time.
What is the best way of passing this date?
The options I consider are:
making separate get parameters for each piece of info (e.g ?startYear=2012&startMonth=09&startDay=23&startHour=....)
this could work, but what if I add more different filters. It will be too busy there. Or it's not an issue?
Passing timestamp. I consider this to be the best option. However when I convert the date to timestamp it gives me incorrect result. The function will be below.
Passing in 2012-09-23 21:00:00 format by pre-processing with encodeURIComponent
Any suggestions?
Date to timestamp conversion (related to point 2):
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}

Categories