Get XML file, based on current date - javascript

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.

Related

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

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.

Javascript number like time regex format

I'm receiving from my database time like hh:mm:ss, and in javascript i would like to put the time like hh:mm
this is my code
var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
}
The function doesn't work well since i receive "false", any help?
Thanks
May be I am missing something in the question, but if you simply want to extract the hh:mm part from hh:mm:ss, then this should work:
// var time = "hh:mm:ss";
var time = "10:01:30";
var splitTime = time.trim().split(":"); // trim to remove any leading and trailing spaces
var formattedTime = splitTime[0] +":"+ splitTime[1];
console.log( formattedTime );
Couldn't you just do the following?:
function formatTime(time) {
var array = time.split(':');
return array[0] + ':' + array[1];
}
The other answer (using split) is undoubtably the easier way to do this.
However, if you're wondering why your regex was not matching, it is because your regular expression was looking for the first (hh) block, and then the second (mm) block, but was then expecting whitespace after that until the end of the line - no allowance for the ss part.
I changed this rather heavy-handedly to allow anything after the mm part until the end of the line. see below.
Also, if you're wondering why your formatTime function returns undefined its because you forgot to return result
var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d).*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
return result;
}
I would consider working with native Date object to do your formatting. This will do a few things for you:
Automatically validate the time value that is being input. No need for regex to do this. Either the input string is valid and the function works, or it is invalid and the function returns NaN.
Give you flexibility in how you work with the value. Need to convert time zones, convert to Unix timestamp, etc.? These are built in methods on Date object.
Gives flexibility on input values. You could potentially you other string input types here if needed as long as they can allow for instantiation of valid Date object. You need to modify regex to allow for multiple input types or anything like that.
Using this approach, example code might look like:
function stripSecondsFromTimeString(time) {
// create data object representing current date
// the date is not really important here other than allowing
// you to format a fully valid Date object with your time fragment
var day = new Date();
var dateInput = day.toDateString() + ' ' + time;
var date = new Date(dateInput);
// validate we were able to get useful Date object
if(isNaN(date.getHours())) {
return NaN;
}
// log out some values so you can see how you might more fully work with Date object
console.log(date.toString());
console.log(date.getDate());
console.log(date.getHours());
console.log(date.getMinutes());
// prepare to return string
var hours = '' + date.getHours();
if(hours.length === 1) {
hours = '0' + hours;
}
var minutes = '' + date.getMinutes();
if(minutes.length === 1) {
minutes = '0' + minutes;
}
return hours + ':' + minutes;
}
// Usage examples
// your input time fragment
var inputTime = '10:01:30';
var formattedTime = stripSecondsFromTimeString(inputTime);
console.log(formattedTime);
// example failure case
var invalidTime = 'foo';
console.log(stripSecondsFromTimeString(invalidTime));

Customize javascript Date

I have a simple code that echos the current Hour+Minute+Date as one number sequence.
I need to add 1 to all the numbers outputted, individually.
Example: If the current time and date is: 22321512 then i need jQuery to output: 33432623.
My knowledge in jQuery is pretty slim, How can this be achieved?
HTML:
<span id="date"></span>
Code:
var now = dateFormat(new Date(), "HHMMddmm");
$('#date').append(now);
You need to do the following roughly:
var currentDate = new Date();
var myDate = new Date(currentDate.getYear() + 1, currentDate.getMonth() + 1, currentDate.getDay() + 1);
alert(myDate.getTime());
Should solve your problem.
If you want to merely increment each unit by 1 and let the JavaScript engine advance the date and time on overflow, then Captain John's answer will work perfectly.
This means that, for example, if this routine were to be run at 11:59 PM on December 31, your output would be 00000100.
If you want each unit to be incremented by 1 without the date being advanced, you will have to stop relying on Steven Levithan's [excellent] dateFormat library and do it yourself:
var now = new Date(),
hours = now.getHours() + 1, // add 1 hour
minutes = now.getMinutes() + 1, // add 1 minute
date = now.getDate() + 1, // add 1 day
month = now.getMonth() + 1, // add 1 month
padLeft = function (val) { // make a formatter
while (val.length < 2) {
val = '0' + val; // string is less than 2 characters, pad left side with '0'
}
return val; // return formatted string
},
formatted = padLeft(hours) + padLeft(minutes) + padLeft(date) + padLeft(month);
$('#date').append(formatted);
Getting number length as string you can easily sum 1 to each number.
The result is given as timestamp
To get Date object, use new Date(result);
var now = new Date().getTime(); // 22321512 on your example
// Answer
var result = 0;
var str = now.toString();
for(var i = 0; i < str.length; i++) {
result += Math.pow(10, i);
}
result += now; // Ex.: 22321512 + 11111111

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.

Parsing the date in MM/DD/YY format

I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp

Categories

Resources