I use my document _id client-side as strings. I would love to be able pull the timestamp from this value as you can on the server. Is it possible to recreate this functionality on the client side? (recast as objectid, or create a standalone function to pull this data)
example _id: "4f94c2a11a6bbec3872cb315"
Thanks!
How about this, broken down into steps... unfortunately it's only second resolution time that gets stored in the ObjectID.
var id = "4f94c2a11a6bbec3872cb315";
// first 4 bytes are the timestamp portion (8 hex chars)
var timehex = id.substring(0,8);
console.log(timehex); // gives: 4f94c2a1
// convert to a number... base 16
var secondsSinceEpoch = parseInt(timehex, 16);
console.log(secondsSinceEpoch); // gives: 1335149217
// convert to milliseconds, and create a new date
var dt = new Date(secondsSinceEpoch*1000);
console.log(dt); // gives: Sun Apr 22 2012 22:46:57 GMT-0400 (EDT)
See jsfiddle if you want to test: http://jsfiddle.net/pZdyM/
NOTE: this is kind of kludgy--it depends on the current ObjectID format. They might move the timestamp around within the ObjectID one day, and that would break this.
Related
I want to run a query in mongo which will get data till 7:00 am, then 7 am to 11 am and then 12 pm to 4 pm of particular that day only. Now these time are stored in different timezone. So I want to know how get data from mongo.
I tried using momentJs to get the the time range but not able to get correct timezone.
var dayStart = moment().zone(timezone).startOf('day');
var now = moment().zone(timezone);
var duration = moment.duration(now - dayEnd);
and my mongo query is
db.CollectionName.find({"created_at": {
'$gte': dayStart,
'$lt': now
}});
I want the three result seperately that is till 7am, 7am-11am & 12pm-4pm. Any help please.
I would still advise against using moment().zone() - at the very least use moment().utcOffset() as it more clearly communicates the approach of the function. However, since you are using .zone() now I will share an example to get you started.
We assume the following:
when a record is saved to your database, the created_at value defaults to UTC
you are the only user of concern
you are located in the Kolkata timezone and when you say 7am, you expect it to be relative to that location on earth
Using the zone feature, you would then need to a value of -330 to translate from UTC to Kolkata. (Since Kolkata is UTC+5:30, we must convert to minutes and then subtract that value 5 * 60 + 30 = 330.)
Given all of that, your values will be as follows:
var dayStart = moment().utc().zone(-330).startOf('day');
var now = moment().utc().zone(-330);
var duration = moment.duration(now.diff(dayStart)).as('minutes');
you had a few typos in your example: dayEnd was an undefined variable, I assumed you meant to use dayStart. also, duration needs to use diff and an argument to format the output, I have used minutes for this example.
You can test further and play around with this example:
https://jsfiddle.net/dusthaines/48wubezy/5/
I have this TimeStamp = "2017-08-02T08:00:38.977" which is provided to me from 3rd party API feed. It is already in UTC.
I need to log this into mongo and I want it to be a valid Date type in mongo for querying but I'm struggling to convert the damn thing correctly so it's stored 'as is'.
e.g.
TimeStamp = new Date(TimeStamp) gives me Wed Aug 02 2017 08:00:38 GMT+0800 which when I insert to mongo appears as 2017-08-02 00:00:38.280Z i.e. "TimeStamp" : ISODate("2017-08-02T00:00:38.280Z")
I tried toISOString and various other things but they all change the time in bizarre ways and appear in mongo completely different to what i expect.
Can someone please tell me how to just insert the string variable 2017-08-02T07:55:47.977 into mongo so it remains exactly the same but is Date type.
Regards
fLo
Update
Incoming string timestamp from API = 2017-08-02T08:30:41.39
new Date(TimeStamp) = 2017-08-02T00:30:41.390Z
Document in Mongo after insert = "TimeStamp" : ISODate("2017-08-02T00:30:41.390Z")
In database i have a row with date & time, say 2014-04-16 00:00:00 then I convert that datetime to unix timestamp using
strtotime('2014-04-16 00:00:00') * 1000; // result 1397577600000
In javascript i am trying to get the hour using the following code
var d = new Date(1397577600000); // 1397577600000 from php unix timestamp in previous code
d.getHours(); // return 23
d.getMinutes(); // return 0
why getHours() return 23 instead of 0? is there any difference between js timestamp and php timestamp?
Date objects in javascript will always return values based on the browser's current timezone. So if d.getHours() is returning 23 for you, that would suggest your local browser timezone is one hour earlier than UTC (-01:00).
It you want the hours for a Date object based on UTC timezone, you can use:
d.getUTCHours()
Follow Up:
Just to throw out some free advice, you could use the following code to deal with your date values from one context to another:
PHP:
// Fetched from the db somehow
$datetime_db = '2014-04-16 00:00:00';
// Convert to PHP DateTime object:
$datetime_obj = new DateTime($datetime_db, new DateTimeZone('UTC'));
// Format DateTime object to javascript-friendly ISO-8601 format:
$datetime_iso = $datetime_obj->format(DateTime::W3C);
Javascript:
var d = new Date('2014-04-16T00:00:00+00:00'); // 2014-04-16T00:00:00+00:00 from PHP in previous code
d.getUTCHours(); // returns 0
This keeps the datetime variables in a language-specific object format when being handled in that language, and serializes the value into a string format that all current browsers/languages accept (the international standard ISO-8601).
I am getting 21 here because in Javascript local timezone of the user will be considered to fetch time and date.
Ok, based on what Arun P Johnny said.
I change the strtotime parameter to match my timezone, in this case i changed it to
strtotime('2014-04-16 00:00:00 GMT+7') * 1000;
hope this help anybody that have the same problem as I.
I have an MVC 3 web application for a web API, a controller emit json.
In the json result I see dates are being serialised automatically
as
{
Flag: "U"
EventId: "168ef1d4-60ca-4fa1-b03b-8c3207650347"
EventTitle: "test event 11"
DateTimeStart: "/Date(1369217469310)/"
IsCustomEvent: true
Location: null
}
in javascript I need to convert DateTimeStart in human readable format and using this code
var date = new Date(1369217469310);
alert(date);
I see the resulting data as
Wed May 22 2013 12:11:09 GMT+0200 (CEST)
This is 1 hour a head of the date stored in the application wich is 22/05/2013 11:11:09.
I would like to know where the issue could be and how to fix it:
Is it .Net serialising dates by default using CEST wich is +1 UCT, in this case how to set up UCT at 0?
Is it an issue when converting in the date using JavaScript?
Please let em know how you would fix it, thanks!
I haven't enough information to advice about the server side. Generally the source of the problem on server side may be the CultureInfo set in you application. You may consider to convert all datetimes as UTC before sending it to the browser. Check the DateTime.ToUniversalTime() method.
On client side you also are able to fix the offset between regional time and UTC. There is no build in function to do this, but it's very simple operation to perform. Check the code below.
var date = new Date();
var dateWithOffset = date.getTime() + date.getTimezoneOffset() * 60000;
I'm storing Utc datetime on the server and requesting data via json to display on client.
The problem is that the server returns the time by its timezone which is different to a client.
How could I get the local dateTime to display on client without hardcoding the offset?
I'm using asp.net mvc and stroring date and time in SQL Server 2008 database as 'datetime'. DateTime format in database is 2013-03-29 08:00:00.000.
You don't say how the UTC time is represented. It's common to use a UNIX time value that is seconds since 1970-01-01T00:00:00Z. If that is what you are using, you can create a date object on the client by multiplying by 1,000 and giving it to the Date constructor:
var unixTimeValue = '1364694508';
var clientDateObject = new Date(unixTimeValue * 1000);
If you are using say .NET, the value may already be in milliseconds so you don't need to multiply by 1,000. You need to check with the source to see what value is passed and what epoch is used if it's a time value.
Javascript date objects are based on a time value that is the same epoch as UNIX, but uses milliseconds. The standard Date methods (getFullYear, getMonth, getDate, etc.) will return values in the local timezone based on system settings. The UTC methods (getUTCFullYear, getUTCMonth, getUTCDate, etc.) return UTC values for the same time.
So if you are passing a time value, use it to create a date object on the client and read the values using standard methods and you have local equivalents of the UTC time value.
If you are passing a datetime string like 2013-03-31T14:32:22Z, you can convert that to a date object using Date.UTC to convert the string to a time value, then give that to the date constructor:
function dateFromUTCString(s) {
s = s.split(/[-T:Z]/ig);
return new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5]));
}
var s = '2013-03-31T14:32:22Z';
alert(dateFromUTCString(s)); // Mon Apr 01 2013 00:32:22 GMT+1000 (EST)
If your input string is a different format, you may need to adjust the split pattern and order of parameters passed to Date.UTC.
Edit
If the string format is 2013-03-29 08:00:00.000 (assuming UTC), you can use:
function dateFromUTCString(s) {
s = s.split(/[\D]/ig);
return new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5], s[6]||0));
}
var s = '2013-03-29 08:00:00.000';
alert(dateFromUTCString(s)); // Fri Mar 29 2013 18:00:00 GMT+1000 (EST)
But be careful of additional spaces. You might want to trim any leading or trailing spaces and ensure there is only one separating the date and time components.
Edit 2
Don't use Date.parse. Until ES5 it was completely implementation dependent. Now it's partially standardised if the string complies with the ISO8601–like format specified by ES5. But that isn't supported by all browsers in use, so not reliable and is otherwise still implementation dependent. The best solution (i.e. one that will work everywhere) is to manually parse the value you are given.
If the format is like: "1364835180000-0700", then you can fairly easily deal with that using a function that subtracts the offset to get UTC time value, the gives that to the date constructor. I'm assuming that -0700 means 7hrs west of Greenwich (javascript timezone offsets have an opposite sense, west of Greenwich is +ve).
Edit 3
Sorry, must have posted the wrong snipped, rushing to a meeting.
// Where s is a time value with offset
function toDate(s) {
// Include factor to convert mins to ms in sign
var sign = s.indexOf('-') > -1? 6e4 : -6e4;
s = s.split(/[\+\-]/);
var l = s[1].length;
// Convert offset in milliseconds
var offset = sign*s[1].substring(l-2,l) + sign*s[1].substring(l-4, l-2)*60;
// Add offset to time value to get UTC and create date object
return new Date(+s[0] + offset);
}
var s = "1364835180000-0700"
alert(toDate(s)); // Tue Apr 02 2013 09:53:00 GMT+1000 (EST)
Return the DateTime as UTC and convert it on the client using .toLocaleString():
#ViewBag.Time = Model.Time.ToUniversalTime().Ticks / TimeSpan.TicksPerMillisecond
<script>
var time = new Date(#ViewBag.Time);
var localTimeString = time.toLocaleString();
alert(localTimeString);
</script>