Port Of PHP's Date() Function To Javascript

Dec 7, 2002

Okay, this an attempt to port PHP's date() function as much as possible to JavaScript. Could use some refactoring though. Any critique, comments, appraisal and any other opinion is very welcome. Feel free to discuss and also take a look at beetles code here: http://www.codingforums.com/showthread.php?s=&threadid=11069

Oh, and the date() function is described here: http://www.php.net/manual/en/function.date.php


Date.prototype.monthNames = new Array(
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
);


Date.prototype.dayNames = new Array(
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
);


Date.prototype.format = function (formatStr) {
var heap = formatStr.split("");
var resHeap = new Array(heap.length);
var escapeChar = ""; // you can change this to something different, but
// don't use a character that has a formatting meaning,
// unless you want to disable it's functionality

// go through array and extract identifiers from its fields
for (var i = 0; i < heap.length; i++) {
switch(heap[i]) {
case escapeChar:
resHeap[i] = heap[i+1];
i++;
break;

case "a": // "am" or "pm"
var temp = this.getHours();
resHeap[i] = (temp < 12) ? "am" : "pm";
break;

case "A": // "AM" or "PM"
var temp = this.getHours();
resHeap[i] = (temp < 12) ? "AM" : "PM";
break;

case "d": // day of the month, 2 digits with leading zeros; i.e. "01" to "31"
var temp = String(this.getDate());
resHeap[i] = (temp.length > 1) ? temp : "0" + temp;
break;

case "D": // day of the week, textual, 3 letters; i.e. "Fri"
var temp = this.dayNames[this.getDay()];
resHeap[i] = temp.substring(0, 3);
break;

case "F": // month, textual, long; i.e. "January"
resHeap[i] = this.monthNames[this.getMonth()];
break;

case "g": // hour, 12-hour format without leading zeros; i.e. "1" to "12"
var temp = this.getHours();
resHeap[i] = (temp <= 12) ? temp : (temp - 12);
break;

case "G": // hour, 24-hour format without leading zeros; i.e. "0" to "23"
resHeap[i] = String(this.getHours());
break;

case "h": // hour, 12-hour format; i.e. "01" to "12"
var temp = String(this.getHours());
temp = (temp <= 12) ? temp : (temp - 12);
resHeap[i] = (temp.length > 1) ? temp : "0" + temp;
break;

case "H": // hour, 24-hour format; i.e. "00" to "23"
var temp = String(this.getHours());
resHeap[i] = (temp.length > 1) ? temp : "0" + temp;
break;

case "i": // minutes; i.e. "00" to "59"
var temp = String(this.getMinutes());
resHeap[i] = (temp.length > 1) ? temp : "0" + temp;
break;

case "I": // "1" if Daylight Savings Time, "0" otherwise. Works only on the northern hemisphere
var firstDay = new Date(this.getFullYear(), 0, 1);
resHeap[i] = (this.getTimezoneOffset() != firstDay.getTimezoneOffset()) ? (1) : (0);
break;

case "J": // day of the month without leading zeros; i.e. "1" to "31"
resHeap[i] = this.getDate();
break;

case "l": // day of the week, textual, long; i.e. "Friday"
resHeap[i] = this.dayNames[this.getDay()];
break;

case "L": // boolean for whether it is a leap year; i.e. "0" or "1"
resHeap[i] = (this.getFullYear() % 4) ? false : true;
break;

case "m": // month; i.e. "01" to "12"
var temp = String(this.getMonth() + 1);
resHeap[i] = (temp.length > 1) ? temp : "0" + temp;
break;

case "M": // month, textual, 3 letters; i.e. "Jan"
resHeap[i] = this.monthNames[this.getMonth()];
break;

case "n": // month without leading zeros; i.e. "1" to "12"
resHeap[i] = this.getMonth() + 1;
break;

case "O": // Difference to Greenwich time in hours; i.e. "+0200"
var minZone = this.getTimezoneOffset();
var mins = minZone % 60;
var hour = String(((minZone - mins) / 60) * -1);

if (hour.charAt(0) != "-") {
hour = "+" + hour;
}

hour = (hour.length == 3) ? (hour) : (hour.replace(/([+-])(d)/, "$1" + 0 + "$2"));
resHeap[i] = hour + mins + "0";
break;

case "r": // RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200"
var dayName = this.dayNames[this.getDay()].substr(0, 3);
var monthName = this.monthNames[this.getMonth()].substr(0, 3);
resHeap[i] = dayName + ", " + this.getDate() + " " + monthName + this.format(" Y H:i:s O");
break;

case "s": // seconds; i.e. "00" to "59"
var temp = String(this.getSeconds());
resHeap[i] = (temp.length > 1) ? temp : "0" + temp;
break;

case "S": // English ordinal suffix for the day of the month, 2 characters; i.e. "st", "nd", "rd" or "th"
var temp = this.getDate();
var suffixes = ["st", "nd", "rd"];
var suffix = "";

if (temp >= 11 && temp <= 13) {
resHeap[i] = "th";
} else {
resHeap[i] = (suffix = suffixes[String(temp).substr(-1) - 1]) ? (suffix) : ("th");
}
break;


case "t": // number of days in the given month; i.e. "28" to "31"
resHeap[i] = this.getDay();
break;

/*
* T: Not implemented
*/

case "U": // seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
// remember that this does not return milisecs!
resHeap[i] = Math.floor(this.getTime() / 1000);
break;

case "w": // day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
resHeap[i] = this.getDay();
break;


case "W": // ISO-8601 week number of year, weeks starting on Monday
var startOfYear = new Date(this.getFullYear(), 0, 1, 0, 0, 0, 0);
var firstDay = startOfYear.getDay() - 1;

if (firstDay < 0) {
firstDay = 6;
}

var firstMonday = Date.UTC(this.getFullYear(), 0, 8 - firstDay);
var thisDay = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate());
resHeap[i] = Math.floor((thisDay - firstMonday) / (1000 * 60 * 60 * 24 * 7)) + 2;
break;

case "y": // year, 2 digits; i.e. "99"
resHeap[i] = String(this.getFullYear()).substring(2);
break;

case "Y": // year, 4 digits; i.e. "1999"
resHeap[i] = this.getFullYear();
break;

case "z": // day of the year; i.e. "0" to "365"
var firstDay = Date.UTC(this.getFullYear(), 0, 0);
var thisDay = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate());
resHeap[i] = Math.floor((thisDay - firstDay) / (1000 * 60 * 60 * 24));
break;

case "Z": // timezone offset in seconds (i.e. "-43200" to "43200").
resHeap[i] = this.getTimezoneOffset() * 60;
break;

default:
resHeap[i] = heap[i];
}
}

// return joined array
return resHeap.join("");
}

View 3 Replies


ADVERTISEMENT

Javascript Port Watching

Nov 7, 2005

Basically, I want to have a javascript that will watch for data coming
in on a specific port - like HTTP on port 80, etc. Is this at all
possible with pure javascript?

View 3 Replies View Related

JS Equivalent To PHPs $$?

Mar 10, 2010

I'm trying to find out if javascript has something akin to $$ in php.What I'm trying to do:

var costs = {
cost1: 5,
cost2: 10,
cost3: 15
}

// Retrieve cost user has selected

alert(costs.selectedCost);

Its obviously a hyper-simplified example of what I'm trying to do, but the premise is the same. In PHP, I could use $$ to convert one variable into another, not sure if JS can do the same.

View 6 Replies View Related

Date Range For Date Function

Jul 23, 2005

What is the maximum valid date range for the date(yyyy,mm,dd) function.

View 8 Replies View Related

Date Of Birth Validation Function Needed To Add To Existing Function

Mar 24, 2006

I have a function I call to see if people leave form fields empty. I have been asked by a client to check to make sure of the person's date of birth as well. They gave me the script, however, I am unsure how to do implement it. How do I add this to my existing checks? Code:

View 2 Replies View Related

Port Listen/send

Sep 16, 2005

Is JavaScript able to send/listen for data on a specific port? I'm seeking
a solution to real time data interaction with my web server that doesn't
require refreshing the page. I.e., a chat room, where the data can be
broadcast from the server arbitrarily and displayed by the client
browser(s). To accomplish the data transmission can I use JS, or do I need
to augment my client-side platform to something like Java, et al?

View 1 Replies View Related

Connect To Tcp Port Using Script?

Aug 17, 2009

I'm a newbie to javascript programming and I'm seeking on a solution on how to connect to a tcp port using javascript. Basically, we have phone server that is constantly streaming XML data on port 1024 (serverIP:1024). I've ran a packet sniffer and was able to gather the elements and attributes for the XML data that the server is streaming. Now, I have a test XML parser which works with the XML document using the elements and attributes i've gathered from the packet sniffer. Is there a way for me to connect to the TCP port i've mentioned using javascript and incorporate it with the XML parser that I have. code...

View 3 Replies View Related

Parse USB Port Via Script?

Aug 5, 2009

I am planning to use a USB barcode scanner and use web browsers as my interface.

Is it possible to parse the USB port via javascript? (or any client-side languages)

View 1 Replies View Related

How To Do Serial Port Communication

Aug 31, 2010

How to do serial port communication using Javascript?

View 2 Replies View Related

JQuery :: Changing Datepicker's Date Format Of Selected Date From Date Picker

Mar 16, 2011

I am having difficulty trying to change the format of selected date from date picker. This is a test so my code is very simple. Here it is.

[Code]....

View 1 Replies View Related

JavaScript Date Validation

Feb 8, 2003

Recently while messing with dates, I noticed an odd quirk in javascript with new Date(), i.e. if someone enters an invalid date, such as 2/29/2003, javascript creates the new date as 3/1/2003.

Having a look around, I couldn't find any scripts that took advantage of this for the sake of date validation... probably someone here has done this before, but I'll post it anyway.

The idea is that if javascript creates a new Date() with a different month, then obviously the date entered is not valid. Most of the scripts I saw used some math to divide by leap year, yadda yadda yadda, but with this feature (?) of javascript, it seems unnecessary.

Right now this code only validates mm/dd/yyyy, but it should be easy to modify to support other formats:


function isDate(sDate) {
var re = /^d{1,2}/d{1,2}/d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] && d.getFullYear() == dArr[2];
}
else {
return false;
}
}


Here's a shorter version that works if you pass in the values separately:


function isDate(mm,dd,yyyy) {
var d = new Date(mm + "/" + dd + "/" + yyyy);
return d.getMonth() + 1 == mm && d.getDate() == dd && d.getFullYear() == yyyy;
}

View 3 Replies View Related

Problem With Javascript Date()

Nov 15, 2005

I have written a javascript to compare current date with the date that user has entered in the form. the user enters in YYYY-MM-DD format. here'z the code:

var today= new Date();
var stDate= new Date(document.form[0].startDate.value);
var day=0; var month=0; var year=0;
var todayStr;
day= today.getDate();
month= today.getMonth()+1;
year= today.getFullYear();
todayStr= new Date(year + "-" + month + "-" + day);
alert(todayStr);
if(todayStr>stDate)
{ alert("Current date is greater");}

but todayStr gives NaN . and comparison gives no result.

View 16 Replies View Related

Displaying Date Using Javascript

May 14, 2006

I am trying to use javascript code so that on loading of a webpage, the page displays the day, date, month and year words. So far I have come up with the following but it doesnt seem to be working: Code:

View 3 Replies View Related

Validating Date W/ Javascript

Oct 23, 2001

Im trying to validate my date textbox on my form to only allow mm/dd/yy. If the user enters anything else in I want it to display an error message and focus on the date textbox. Ive looked at many sample scripts with no luck. Anyone out there done this before, and possibly still have the code?

View 2 Replies View Related

Javascript Date Subtractor

Jun 7, 2006

I have a date function that subtract a certain amount of days from todays date.

Code:
function printDate(offset)
{

var offsetAmount= offset
var currentTime= new Date()
var month= currentTime.getMonth() + 1
var day= currentTime.getDate()
var nDay= day - offsetAmount
var year= currentTime.getFullYear()

document.write(nDay + "/" + month + "/" + year)

}
I need it to be able to recognise when it goes into a previous month (ie instead of 0/6/2006 it will go to 31/5/2006)

View 3 Replies View Related

JavaScript Date Validator.

Jun 14, 2007

Is there any function in JavaScript which validates the date format like isNaN() for numbers? Or have anyone made such function which validates the date entered in the text box i.e. dd-mm-yyyy or yyyy-mm-dd or mm-dd-yyyy or dd/mm/yyy or mm/dd/yyyy or yyyy/mm/dd are only the valid dates??

View 1 Replies View Related

How To Send Data To Parallel Port

Mar 30, 2009

I have been directed from .NET section to this section. My original post and question are here. forums.devshed.com/net-development-87/asp-net-how-to-send-data-to-parallel-port-600691.html

Is it possible to send data to parallel port using javascript?

View 2 Replies View Related

JQuery :: Date Range - Start Date And End Date Text Boxs

Feb 6, 2010

I have a start date and end date text boxs. What I would like to achieve is when a submit button is clicked all the available dates between start and end dates should be displayed together with 3 check boxes next to each date (please see below). I am just wondering whether that'sachievablewith jquery, and if so, how I might be able to implement this.

Start date End date

View 8 Replies View Related

Javascript Default Date Is One Month Off

Dec 6, 2005

I just noticed that all my javascript months are off by one month.....didn't test multiple systems tho and my system date is fine.

Any way of fixing this?

View 2 Replies View Related

Javascript Equivalent For Vbscript Date()-1

Mar 28, 2007

I'm looking to return DATE ONLY for yesterday's date. No seconds,
milliseconds. Formatted either yyyy/mm/dd or mm/dd/yyyy. VB does it so
easily Date()-1 will return 03/27/2007 if today is 03/28/2007. Why so
many hoops for javascript? Any ideas?

View 21 Replies View Related

How Do I Format The Last-Modified Date With Javascript?

May 7, 2007

Apparently, ` new Date() ` reads it correctly, though problems
can occur if the browser returns only two digits for the year.
In particular, time zone, field order and separators may vary.
It is also reliant on the server's clock having been correctly
set at the time of upload. See the URL below.

View 1 Replies View Related

JQuery :: AJAX Calls To A Server On A Different Port?

Nov 3, 2010

I know about the same-origin policy and that one of the only ways to load data from a cross-domain is to load it as JSON. However, all I am trying to do is access data from a server on another port (which I believe the browser still treats as cross-domain). I need to do this because the server my application is on is a map server and the other server (Apache) is the only one that can handle php scripts. I have also tried out the plug-in from [URL] and while it works when I do $('#phpContent').load('http://www.google.com'); it doesn't work when I try $('#phpContent').load('http://localhost:80/mapScripts/getFiles.php'); I have also tried$.get('http://localhost:80/mapScripts/getFiles.php', function(data) { $('#phpContent').html(data); });

So here I am breaking my brain and do not know what else to attempt.

View 1 Replies View Related

JQuery :: Cross Port Library Call?

May 13, 2009

I have created a payment system using Jquery. The problem I run into is when I move from http to https. I get the following error: Error: [Exception... "Access to restricted URI denied" code: "1012"

[Code]...

View 3 Replies View Related

Javascript For Converting Given Date To The Required Timezone

Jul 20, 2005

I have date(ex., Thu, 04 Dec 2003 10:35:19 +0500) and I know the
timezone(ex., America/Anchorage). Now I need to convert the date into
the given timezone. Is it possible to achieve this thru js api's?

View 1 Replies View Related

JQuery :: Sliding Elements Into View Port On Click

Jun 21, 2010

Hides the element by sliding it down.
$("div").click(function () { $(this).hide("slide", { direction: "down" }, 1000); });
I am new to Jquery. How do I reverse this code to slide element into viewport as opposed to slide out of view port. This is the link to the effect [URL]. What I want to do is the element will be hidden originally on loading the page and then slides into view with a click anywhere on the page, an anchor or after a few seconds.

View 1 Replies View Related

Establish Serial Port Communication Using Script For Webpage?

Apr 6, 2009

I am working on a robot project, that is required to create a website to control the robot via serial port.. The website is plainly html, no linking to database is needed...

I have no idea how and what language to use and can JavaScript communicate with serial port? and how?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved