Convert 17-digit precision unix time (UTC) to date fromat In javascript - javascript

I got time token like this from 14512768065185892 from PubNub.I need to convert this time token into following format dd/mm/yy.
Any one please provide one method to convert time stamp to date format.
Thanks In Advance

The Date constructor can be passed a time value that is milliseconds since the epoch (1970-01-01T00:00:00Z). The value you have seems to have 4 digits too many, so just divide by 1e4 (or whatever value is appropriate):
var timeValue = 14512768065185892;
document.write(new Date(timeValue/1e4));
There are plenty of questions and answers here on how to format the output as dd/mm/yy (which is a very ambiguous format), e.g.
function formatDMYY(d) {
function z(n){return (n<10?'0':'') + n}
return z(d.getDate()) + '/' + z(d.getMonth() + 1) + '/' + z(d.getFullYear()%1e3);
}
document.write(formatDMYY(new Date(14512768065185892/1e4)));

You can just remove the last 4 characters, and use this timestamp in Date constructor:
new Date(+str.substr(0, str.length - 4))
However, JS doesn't support "dd/mm/yyyy" format, and you will have to implement it yourself or use third-party libraries like Moment.js.
Here is the working demo:
Date.parsePubNub = function(str) {
return new Date(+str.substr(0, str.length - 4));
};
Date.prototype.toDDMMYYYY = function()
{
return ("0" + this.getDate()).slice(-2) + "/" + ("0" + (this.getMonth() + 1)).slice(-2) + "/" + this.getFullYear();
};
var str = "14512768065185892";
document.body.innerText = Date.parsePubNub(str).toDDMMYYYY();

PubNub times have an extra 7 digits of precision above standard UNIX time stamps (seconds) so the first step is to divide it by 107. That gives you 1451276806 which, when you test it in a converter, you get 12/28/2015 # 4:26am (UTC) (using the frankly bizarre(1) US date format) so it seems to be reasonable.
In terms of using Javascript to do this, you can pass the number of milliseconds to Date to have an object instantiated for you:
var dtobj = new Date(1451276806518);
keeping in mind that the millisecond value entails you dividing by 104 (lopping off the final four digits) rather than 107.
Once you have the date object, you can use standard methods to get it in the format you want, such as:
var dtobj = new Date(1451276806518);
var dtdd = ('0' + (dtobj.getDate())).slice(-2);
var dtmm = ('0' + (dtobj.getMonth() + 1)).slice(-2);
var dtyy = ('0' + (getFullYear() % 100)).slice(-2);
document.write(dtdd + "/" + dtmm + "/" + dtyy);
(1) I swear some committee must have taken the worst bits from all date formats to indicate what needed to be discarded, then some other committee accidentally took that as a recommendation. Needless to say, I'm a big fan of ISO 8601 :-)

Related

Combine date formatting vars and functions (jquery/Javascript)

I have a bit of javascript that gets different date ranges and formats them to return yyyymmdd. I get the final result I need, but something about having 2 different variables bugs me and makes me think I am not doing this the best way. I am wondering if there is a way to pass the new date and the additional removal of - all in one line.
my function is:
function toJSONLocalMonth (firstDay, lastDay) {//set default date range to from beggining of this month
var local = new Date(firstDay);
local.setMinutes(firstDay.getMinutes() - firstDay.getTimezoneOffset());
return local.toJSON().slice(0, 10);
var local = new Date(lastDay);
local.setMinutes(lastDay.getMinutes() - lastDay.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
And whenever I need the result I do this:)example of today and yesterday)
var dateToday = new Date();
dateTodayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");//format date yyyymmdd
dateYesterday = dateToday.setDate(dateToday.getDate() - 1);
dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");
If there a better way to get this result, or at the very least combine the dateYesterday and dateYesterdayFormat to a single line to get yyymmdd.
(I need to keep the - in the function result, so I can't filter it there.)
Thanks!
Your question is unclear.
toJSONLocalMonth will only return one value, the one from the first return statement. The second is never reached.
The return value from dateToday.setDate(...) is a time value (a number), not a Date so you can't chain a string method to it. It modifies the date itself so dateYesterday is redundant, i.e.
dateYesterday = dateToday.setDate(dateToday.getDate() - 1);
dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");
can be:
dateToday.setDate(dateToday.getDate() - 1);
var dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");
The toJSONLocalMonth seems to be just getting a date string formatted as YYYYMMDD. I guess you're avoiding the built–in ISO methods because they use UTC/GMT and not the local time zone. The following function does that in a more obvious way:
/* Return an ISO 8601 formatted date string
** #param {Date} d - date to create string for
** #returns {string} string formatted as ISO 8601 without timezone
*/
function toISOStringLocal(d) {
function z(n){return (n<10?'0':'') + n}
return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
z(d.getDate()) + 'T' + z(d.getHours()) + ':' +
z(d.getMinutes()) + ':' + z(d.getSeconds())
}
console.log(toISOStringLocal(new Date));
You might also consider a small formatting library like fecha.js where you'd do:
var dateToday = new Date();
var dateTodayFormat = fecha.format(dateToday, 'YYYYMMDD')
dateToday.setDate(dateToday.getDate() - 1);
var dateYesterdayFormat = fecha.format(dateToday, 'YYYYMMDD');
The last two lines could become one using:
var dateYesterdayFormat = fecha.format(new Date(dateToday.setDate(dateToday.getDate() - 1)), 'YYYYMMDD');
but I wouldn't recommend that.
Also see: Where can I find documentation on formatting a date in JavaScript?

Format date from UTC string

I have a time stamp in a JSON string that I want to break down. The format of the string is
"generatedAt": "2015-01-30T16:01:31.4019286+00:00",
This is consistent in terms of characters and numbers counts
I basically want to extract (in Javascript / JQuery)
generatedDate // the first part of the string up to the letter T
generatedTime // the xx:xx:xx after the letter T
so in this example generatedDate = '2015-01-30', and generatedTime = '16:01'
There is a chance that this rendering of date time is a standard I just don't recognise and may be easily rendered with extracting parts of it.. but I don't recognise it so thats moot
Any assistance greatly appreciated
The value in the property can be converted to a date quite easily using the Date type:
var date = new Date("2015-01-30T16:01:31.4019286+00:00");
From there you can retrieve the parts of the date as required:
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).substr(-2) + '-' + ("0" + date.getDate()).substr(-2);
var timeString = ("0" + date.getHours()).substr(-2) + ':' + ("0" + date.getMinutes()).substr(-2);
alert(dateString); // = "2015-01-30"
alert(timeString); // = "16:01"
Example fiddle
You can simplify this massively if you use a date format library such as DateJS or MomentJS

Is there any way to format the date of a field in a query? [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I am getting a query with a field in an undesired date format (Thu Feb 21 00:00:00 EST 2013)
Is there any way to modify this to mm-dd-yyy?
I am using javascript, I found a php way to do it, but sadly it has to be in javascript, so the instruction has to be pretty much the same way it would be in TOAD.
I tried the CONVERT() method and it didn't work. I am not sure I am using it right though
The Convert() function will work, but you need to use the correct format code from here:
SQL Convert() Function.
SELECT Convert(char(10), #date, 110)
Date.js is pretty handy for date formatting.
you probably could try converting to a unix timestamp, then formatting. I havent tested this, and it will probably throw an error, but you get the idea.
var input = your date;
input = input.split(" - ").map(function (date){
return Date.parse(date+"-0500")/1000;
}).join(" - ");
var year = input.getYear();
var month = input.getMonth();
var day = input.getDay();
var hours = input.getHours();
var minutes = input.getMinutes();
var seconds = input.getSeconds();
var formatted = month + " " + day + ", " + year + " at " hours + ':' + minutes + ':' + seconds;
There are basic Date object functions in JS that you can use.
First, create the date variable:
var date = new Date('your date value');
Then you can access the individual date pieces:
var month = date.getMonth() + 1; //gets the month . . . it's 0-based, so add 1
var day = date.getDate(); //gets the day of the month
var year = date.getFullYear(); //gets the 4-digit year
Once you have those values, you can concatenate them in any format that you'd like. For a basic mm-dd-yyyy, use:
var formattedDate = month + "-" + day + "-" + year;
There time and timezone values are also available.
That's a badly mixed up format. There are two basic ways to modify it, one is to just re–order the bits you have, the other is to convert it to a date object and use that to create the new string. Either way, you haven't said what to do with the timezone offset.
Using abbreviations or names for timezones is ambiguous, there is no standard for them and some are duplicted (EST is used for three different timezones). In any case, a simple re–ordering can be:
function formatDate(s) {
var months = {jan:'01', feb:'02', mar:'03', apr:'04',
may:'05', jun:'06', jul:'07', aug:'08',
sep:'09', oct:'10', nov:'11', dec:'12'};
var s = s.split(' ');
var d = (s[2] < 10? '0' : '') + s[2];
return months[s[1].toLowerCase()] + '-' + d + '-' + s[5];
}
alert(formatDate('Thu Feb 21 00:00:00 EST 2013')); // 02-21-2013
The output format (mm-dd-yyyy) is ambiguous, consider using something like 21-Feb-2013 or a standard format like ISO8601 (2013-02-21).
If you need to consider the timezone, it will be easier to create a date object, add the offset, then get back the new date. However, you will also need to work out how to convert the string timezone to a number (preferably minutes, but hours is OK) that can be used with the date.

Get GMT String from current Date

I am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)
var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');
Any ideas? The output looks like:
20120403031408
I am able to get the GMT in standard string format by doing:
dt.toUTCString();
but im unable to convert it back to the yyyyMMddhhmmss string
EDIT: I am using the date.js library
date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.
You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:
var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);
// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);
You can also write your own function, as Dominic demonstrated.
The key is to use the getUTC functions :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n) { return n < 10 ? '0'+n : n }
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() +1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Javascript date question about format

I've been struggling with javascript more than an hour and came up with a solution - to ask you for help!
A RSS Feed generates the date of every post in this format 2011-05-18T17:32:43Z. How can I make it look like that 17:32 18.05.2011?
Thank you in advance!
Assuming you've parsed the RSS date into a JS Date object (which can be tricky, since many Date.parse implementations don't accept ISO-8601 dates like that)...
//var d=new Date(/*...*/)
// 17:32 18.05.2011
pad(d.getHours())+':'+d.getMinutes()+' '+
pad(d.getDate())+'.'+pad(d.getMonth()+1)+d.getFullYear();
(getMonth returns 0-11 based month)
... you'd also want some kind of zero buffering for the month (in your example) and possibly day, hour (depending)....
function pad(val,len) {
var s=val.toString();
while (s.length<len) {s='0'+s;}
return s;
}
Optionally from string->string you could use:
function reformat(str) {
var isodt=string.match(/^\s*(\-?\d{4}|[\+\-]\d{5,})(\-)?(\d\d)\2(\d\d)T(\d\d)(:)?(\d\d)?(?:\6(\d\d))?([\.,]\d+)?(Z|[\+\-](?:\d\d):?(?:\d\d)?)\s*$/i);
if (isodt===null) {return '';} // FAILED
return isodt[5]+':'+isodt[7]+' '+isodt[4]+'.'+isodt[3]+'.'+isodt[1];
}
You can create a new Date, get the fragments out of it and concatenate everything:
function parse(date) {
var d = new Date(date)
return d.getHours() + ":" + d.getMinutes()
+ " " + d.getDate() + "." + (d.getMonth()+1)
+ "." + d.getFullYear();
}

Categories