Have Javascript recognize YYYYmmdd in +5:00 Time Zone [duplicate] - javascript

I need my date to be in ccyymmdd format to add a day and pass over to a cobol application via xml. I also need to convert the new date with the added day to mm/dd/ccyy format to place into my slickgrid. My boss believes there has to be an easier way however, I can't seem to find one without using jquery or adding another library. Here is the code I am using;
// Roll date for status R1(rolled) today plus 1 day.
var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
(rDate++);
// Convert rDate back to useable date for updating ActionDate when rolling clt.
var uDate = (String(rDate)).replace(/(\d{4})(\d{2})(\d+)/, "$2/$3/$1");

So to preserve what you are doing (adding a day to the date), one solution is:
var rDate = new Date();
rDate.setDate(rDate.getDate() + 1);
var printDate = rDate.getFullYear()+('0'+(rDate.getMonth()+1)).slice(-2)+('0'+(rDate.getDate())).slice(-2);
The advantage here is that rDate is always a real Date object, so you don't have to convert it back - you can just use it for any output format you wish.

The Date object in JavaScript has getFullYear, getMonth, and day methods, which means you can do:
If you had a function pad(num, digits) which pads a number with leading zeroes, you can have:
var str = pad(date.getFullYear(), 4) + pad(1+ date.getMonth(), 2) + pad(date.getDate(), 2)
From Pad a number with leading zeros in JavaScript on stackoverflow, you can get a pad functio:
function pad(n, width) {
n += '';
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}

I don't think it's better, but another approach:
var d = new Date();
var datestr = [ d.getFullYear(), ('0' + (1+d.getMonth())).substr(-2), ("0" + d.getDate()).substr(-2) ].join('');
Two thing to clarify: getMonth() returns 0-based month number, hence the need to add 1. And the ("0" + number).substr(-2) is used to add leading zeroes to single digit numbers, because substr(-2) returns two last characters of a string.

Related

HTML5 Date Validation

I'm looking to implement validation for a mobile site, where I have two input fields and I would like the first to validate the value is no later than todays date, and the second to validate it is no later than a one year in advance of the first value.
E.g
First Value = 26/11/2013
Second Value can not contain a value later than 26/11/2014
Is this possible?
I like moment.js. It makes it easier to deal with dates and times.
First, let's make sure a day "is before tomorrow". This will depend a bit upon what the definition of tomorrow is.
var m = moment("26/11/2013", "MM/DD/YYYY");
// tomorrow this time
var t = moment().add("days", 1);
// tomorrow start of day
var tomorrow = moment([t.year(), t.month(), t.date()]);
if (m.lessThan(tomorrow)) {
// today!!! (or before)
}
Similarly, the same approach can be used for a year from now. It's likely fine enough to not care about the time component in this case, and I've slogged on another day - but if it matters (e.g. looking for the start of the day), see the previous example.
var m = moment("26/11/2013", "MM/DD/YYYY");
var aYearFromNow = moment().add("years", 1).add("days", 1);
if (m.lessThan(aYearFromNow)) {
// still less than a year!
}
1) cache the elements.
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
2) The value of d1 and d2 are string data type. So split them and parse it to date format as below
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
Here the year is incremented by 1, based on the value in d1.
4) Again parse it back to string format (YYYY-MM-DD)
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
5) Set this as value for max attribute for d2
d2.setAttribute("max", maxi);
Finally add the below method to onblur event of d1.
function setMaxDate() {
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
d2.setAttribute("max", maxi);
}
JSFiddle
Better with javascript. You can I use HTML5 attribute type="date" but keep in mind it's barely supported.
You can use a Regex pattern like this /([0-9]{2})/([0-9]{2})/([0-9]{4})/, that is, two decimal digits, a slash, two more decimal digits, a slash and four decimal digits, everything grouped separately (group 1 = day, group 2 = month, group 3 = year). You would test for this pattern in a event, (I would suggest onchange, since you mentioned mobile) and also check if the numbers are within a valid range (e.g. day < 32, month < 13, year < currentYear-1).

JavaScript Time Until

I need to do the simplest thing, take an input date/time and write out the hours:minutes:seconds until that time. I haven't been able to figure it out. I even tried using Datejs which is great, but doesn't seem to have this functionality built in.
The time is going to be somewhere in the range of 0 mins -> 20 minutes
Thanks!
Don't bother with a library for something so simple. You must know the format of the input date string whether you use a library or not, so presuming ISO8601 (like 2013-02-08T08:34:15Z) you can do something like:
// Convert string in ISO8601 format to date object
// e.g. 2013-02-08T02:40:00Z
//
function isoToObj(s) {
var b = s.split(/[-TZ:]/i);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5]));
}
function timeToGo(s) {
// Utility to add leading zero
function z(n) {
return (n < 10? '0' : '') + n;
}
// Convert string to date object
var d = isoToObj(s);
var diff = d - new Date();
// Allow for previous times
var sign = diff < 0? '-' : '';
diff = Math.abs(diff);
// Get time components
var hours = diff/3.6e6 | 0;
var mins = diff%3.6e6 / 6e4 | 0;
var secs = Math.round(diff%6e4 / 1e3);
// Return formatted string
return sign + z(hours) + ':' + z(mins) + ':' + z(secs);
}
You may need to play with the function that converts the string to a date, but not much. You should be providing a UTC timestring anyway, unless you can be certain that the local time of the client is set to the timezone of the supplied datetime value.
Instead of Date.js, try Moment.js.

How to add weeks to date using javascript?

Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.
I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.
My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
document.frmAccept.acceptLicence.value = date1;
}
You can do this :
const numWeeks = 2;
const now = new Date();
now.setDate(now.getDate() + numWeeks * 7);
or as a function
const addWeeksToDate = (dateObj,numberOfWeeks) => {
dateObj.setDate(dateObj.getDate()+ numberOfWeeks * 7);
return dateObj;
}
const numberOfWeeks = 2
console.log(addWeeksToDate(new Date(), 2).toISOString());
You can see the fiddle here.
According to the documentation in MDN
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
This might not answer the question per se, but one can find a solution with these formulas.
6.048e+8 = 1 week in milliseconds
Date.now() = Now in milliseconds
Date.now() + 6.048e+8 = 1 week from today
Date.now() + (6.048e+8 * 2) = 2 weeks from today
new Date( Date.now() + (6.048e+8 * 2) ) = Date Object for 2 weeks from today
You're assigning date1 to be a Date object which represents the string you pass it. What you're seeing in the acceptLicense value is the toString() representation of the date object (try alert(date1.toString()) to see this).
To output as you want, you'll have to use string concatenation and the various Date methods.
var formattedDate = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
In terms of adding 2 weeks, you should add 14 days to the current date;
date1.setDate(date.getDate() + 14);
... this will automatically handle the month increase etc.
In the end, you'll end up with;
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
N.B Months in JavaScript are 0-indexed (Jan = 0, Dec = 11), hence the +1 on the month.
Edit: To address your comment, you should construct date as follows instead, as the Date argument is supposed to be "A string representing an RFC2822 or ISO 8601 date." (see here).
var segments = acceptCompletionDate.split("/");
var date1 = new Date(segments[2], segments[1], segments[0]);
This should do what you're looking for.
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
}
To parse the specific dd/mm/yyyy format and increment days with 14 , you can do something like split the parts, and create the date object with y/m/d given specfically. (incrementing the days right away) Providing the separator is always -, the following should work:
function LicenceToOccupy(acceptCompletionDate)
{
var parts = acceptCompletionDate.split("/");
var date1 = new Date(parts[2], (parts[1] - 1), parseInt(parts[0]) + 14); //month 0 based, day: parse to int and increment 14 (2 weeks)
document.frmAccept.acceptLicence.value = date1.toLocaleDateString(); //if the d/m/y format is the local string, otherwise some cusom formatting needs to be done
}
date1.toLocaleDateString()
Thiswill return you date1 as a String in the client convention
To create a new date date2 with 2 weeks more (2weeks = 27246060 seconds):
var date2 = new Date(date1 + 60*60*24*7*2);

Get XML file, based on current date

I am very new to parsing XML data with javascript, so please excuse me if my question is a bit simple.
I am parsing data from an XMl file with javascript using a standard xmlHTTPRequest. The format of the URL that I am pulling the XML data from is something like: "http://example.com/abcyymmdd-data.xml". The (yymmdd) portion of the url represents the date and the files are updated daily. I would like to insert a javascript code in the url in place of yymmdd so that a new XML file is parsed each day. How might I achieve this?
Thanks,
Carlos
First, to get today's date, use:
var today = new Date;
To get the components, use:
var date = today.getDate();
var month = today.getMonth() + 1; // caveat, starts at 0
var year = today.getFullYear(); // 4 numbers (e.g. 2011)
Now, you need it in the format yymmdd. So you need to remove the two first numbers from year, and prepend a 0 to date and month, if necessary.
function zeropad(number) {
var str = number.toString(); // number to string
return str.length === 1 // if length is 1
? '0' + str // prepend a 0
: str; // otherwise return string without modification
}
And then:
var formatted = year.toString().substring(2) // only the string from the first two numbers and on
+ zeropad(month) // month with 0 prepended
+ zeropad(date); // date with 0 prepended
Then, in your XHR, use:
xhr.open("GET", "http://example.com/abc" + formatted + "-data.xml", true);
You can retrieve the current date in yymmdd format like:
var d = new Date();
var date_string =
d.getFullYear().toString().substring(2) +
(d.getMonth () < 9 ? "0" : "") + (d.getMonth() + 1) +
(d.getDate() < 10 ? "0" : "") + d.getDate();
Example at JS Fiddle.

Adding days to a date - date getting converted to string

So I'm trying to add a certain number of days to a date, and I'm getting a strange issue:
var date = new Date();
var newdate = date.getDate() + $('#ddlDays option:selected').val();
date.setDate(newdate);
So if today is 09/29/2010, the Date is 29. But if a user selects "5" from ddlDays, it will assume I am adding strings together, adding 295 days to my date.
I was under the impression that javascript would assume they were integers? Does getDate() return a string instead of an integer?
How can I fix this?
If you just want to add the selected value to the day of the month (i.e. 29 + 5), then you need to parse the string value into an int:
var newdate = date.getDate() + parseInt( $('#ddlDays option:selected').val(), 10);
But if you actually want a new date, rather than an int, as your result, you can do something like this:
date.setDate( date.getDate() + parseInt( $('#ddlDays option:selected').val(), 10);
It is .val() that is returning a String. You can use .parseInt() to convert to a Number.
var newdate = date.getDate() +
(parseInt($('#ddlDays option:selected').val(), 10) || 0);
or
var newdate = date.getDate() + ~~$('#ddlDays option:selected').val();
No, the getDate() call doesn't return a string, but the val() call does.
You'll need to parse the string to an integer instead:
var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val(), 10);
Surround your string value with parseInt. JavaScript will concatenate strings to numbers (see http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference for a thorough run through.)
This should do the trick:
var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val());
or
var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val(), 10);
adding days and converting it to a specific format are talked about in this question

Categories

Resources