I need to run a check on dates, one being a selected date which I had, the second needs to be the current date + 36 weeks.
I've looked around and every solution I've seen involves GetDate() + days.
new Date().getDate() + 252
This is not working, the date currently is 2014/03/07 so the line above takes 7 and adds 252 which is not correct.
I'm looking for any solution using JavaScript or jQuery.
Thanks in advance.
check jsFiddle
JavaScript Code
var newdate = new Date();
newdate.setDate(newdate.getDate()+252); // 36 week * 7 day = 252
alert(newdate.getFullYear() + "-" + (newdate.getMonth() + 1) + "-" + newdate.getDate()); // alert(newdate);
Did you try the date.setDate() function?
var today = new Date();
today.setDate( today.getDate() + 252 );
Please can someone show me how to make current date = 36 weeks and then parse it into the format 'yyyy-MM-dd'
Everything you need is in other answers, but to make it clear
// Start with a date
var d = new Date();
// Create a new date 36 weeks in the future
var e = new Date(+d + 36*7*24*60*60*1000);
// Convert to ISO 8601 format and get just the date part
alert(e.toISOString().split(/t/i)[0]);
or get the bits and format the string yourself:
function pad(n){return (n<10?'0':'')+n}
alert(e.getFullYear() + '-' + pad(e.getMonth()+1) + '-' + pad(e.getDate()));
Try this:
var now = new Date();
now.setDate(now.getDate()+252);
alert(now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate());
Check in fiddle: http://jsfiddle.net/Uz4VV/
I know you said that you were looking to just use JavaScript and jQuery, but there's a library out there called Moment.js that excels at doing just this.
moment().add('weeks', 36);
It's that easy. Why not give it a go?
Related
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 :-)
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.
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
The Google Feed API outputs the published date in the format: "13 Apr 2007 12:40:07 -0700".
I wish to change that to the valid HTML5 <time datetime="YYYY-MM-DDThh:mm:ssTZD"> using JS/jQuery.
Is there an easy way? Or a library?
Check out JavaScript Date Format. (Download here.) Then it's as easy as:
var input = "13 Apr 2007 12:40:07 -0700";
var date = Date.parse(input);
var output = dateFormat(date, 'yyyy-mm-dd"T"hh:MM:ssoD');
// output == 2007-04-13T12:40:07-0700D
Demo here: http://jsfiddle.net/pkC3s/2/
I started a solution for you in pure javascript by extending the Date object. However, I have to run now.
http://jsfiddle.net/2sYut/
Date.prototype.getHtml5String = function(){
return this.getFullYear() + "-" + this.getMonth() + "-" + this.getDay() + "T" + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds() + "TZ" + this.getTimezoneOffset();
};
var d = new Date( "13 Apr 2007 12:40:07 -0700" );
alert( d.getHtml5String() );
Perhaps you can finish it off (or I will sometime today).
Hope that helps...
In the end I used the formatDate() function found here. The newer JS Toolbox didn't seem to have preserved this function (or at least didn't make it obvious).
var entryDate = new Date(entry.publishedDate); // From Google Feed API
html5date = formatDate(entryDate,'yyyy-MM-ddThh:mm:ss')+entryDate.toString().slice(28,33);
The slicing is to get the timezone, which formatDate didn't seem to support.
Here is the minified function, for preservation:
/*
* Author: Matt Kruse <matt#mattkruse.com>
* http://www.mattkruse.com/
* formatDate (date_object, format)
* Returns a date in the output format specified.
* The format string uses the same abbreviations as in getDateFromFormat()
*/
var MONTH_NAMES="January,February,March,April,May,June,July,August,September,October,November,December,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),DAY_NAMES="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",");function LZ(b){return(0>b||9<b?"":"0")+b} function formatDate(b,f){var f=f+"",h="",g=0,e="",c="",e=b.getYear()+"",c=b.getMonth()+1,i=b.getDate(),j=b.getDay(),d=b.getHours(),k=b.getMinutes(),l=b.getSeconds(),a={};4>e.length&&(e=""+(e-0+1900));a.y=""+e;a.yyyy=e;a.yy=e.substring(2,4);a.M=c;a.MM=LZ(c);a.MMM=MONTH_NAMES[c-1];a.NNN=MONTH_NAMES[c+11];a.d=i;a.dd=LZ(i);a.E=DAY_NAMES[j+7];a.EE=DAY_NAMES[j];a.H=d;a.HH=LZ(d);a.h=0==d?12:12<d?d-12:d;a.hh=LZ(a.h);a.K=11<d?d-12:d;a.k=d+1;a.KK=LZ(a.K);a.kk=LZ(a.k);a.a=11<d?"PM":"AM";a.m=k;a.mm=LZ(k);a.s= l;for(a.ss=LZ(l);g<f.length;){e=f.charAt(g);for(c="";f.charAt(g)==e&&g<f.length;)c+=f.charAt(g++);h=null!=a[c]?h+a[c]:h+c}return h};
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();
}