HTML Date Format - javascript

In HTMl How can I change the format of date? Using date() I got today's date.The problem is I don't know how to change the format of the date. I have to display the date format like this "May 28th 2013". Can any one help me ???
<html position="0,0,0,0" canExport="false">
<![CDATA[
<script>
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var monthname ;
if (month == 1)
monthname = "Jan";
else if (month == 2)
monthname = "Feb";
else if (month == 3)
monthname = "Mar";
else if (month == 4)
monthname = "Apr";
else if (month == 5)
monthname = "May";
else if (month == 5)
monthname = "June";
else if (month == 7)
monthname = "July";
else if (month == 8)
monthname = "Aug";
else if (month == 9)
monthname = "Sep";
else if (month == 10)
monthname = "Oct";
else if (month == 11)
monthname = "Nov";
else
monthname = "Dec";
var day = currentTime.getDate();
var dayname;
if (day == 2 ||day == 22 )
dayname = "nd";
else if (day == 3 ||day == 23 )
dayname = "rd";
else if (day == 1 ||day == 21||day == 31 )
dayname = "st";
else
dayname = "th";
var year = currentTime.getFullYear();
s = currentTime.toDateString();
alert(s);
$('[name=DateDynamic]').text(monthname+" "+day+""+dayname+" "+ year);
</script>
]]>
</html>
Currently I am following the above big method.I know there should be some simple method.

I believe you want this for javascript? Don't you? Assuming your tags
Try something like:
Javascript code:
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
month = getMonthName(month);
var year = currentDate.getFullYear()
document.write("<b>" +month + " " + day + " " + year + "</b>")
function getMonthName(monthNumber)
{
var monthName = "";
switch (monthNumber)
{
case 5:
monthName = "May";
break;
default:
monthName ="not implemented yet";
break;
}
return monthName;
}
Edit--->
I see you have changed your tags. I lieve it up here for anyone!

You can do this using different languages, but I'm guessing you want to use the Date object in Javascript if you're wanting to display a simple date when the page loads.
Here's a tutorial on the many ways to format dates using Javascript:
http://www.w3schools.com/js/js_obj_date.asp

I think the Javascript method toDateString might be want you are looking for:
Documentation
var now = new Date();
x = now.toDateString();
//Fri May 31 2013
//Additional Formatting
var patt = /(\w+) (\w+ [0-9]{1,2}) ([0-9]{4})/;
x = x.replace(patt, '$2, $3');
//May 31, 2013
I put together a Fiddle to handle your 'day suffix' issue.
Output of Fiddle:
//May 31st, 2013

var myDate = new Date();
var formattedDate = myDate.toDateString().split(' ')
formattedDate[0] = '';
if (formattedDate[2][0] != 1 && formattedDate[2][1] == 1) {
formattedDate[2] = formattedDate[2] + 'st';
} else if (formattedDate[2][0] != 1 && formattedDate[2][1] == 2) {
formattedDate[2] = formattedDate[2] + 'nd';
} else if (formattedDate[2][0] != 1 && formattedDate[2][1] == 3) {
formattedDate[2] = formattedDate[2] + 'rd';
} else {
formattedDate[2] = formattedDate[2] + 'th';
}
formattedDate = formattedDate.join(' ');
Output for today: May 31st 2013
http://jsfiddle.net/VHqpU/2/

Based on your example, I cleaned it up a bit. You were also using getDate() for you "day" variable instead of getDay().
<script type="text/javascript">
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var months = ["Dec","Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov",];
var monthname = months[month];
var day = currentTime.getDay();
var dayname;
if (day == 2 ||day == 22 )
dayname = "nd";
else if (day == 3 ||day == 23 )
dayname = "rd";
else if (day == 1 ||day == 21||day == 31 )
dayname = "st";
else
dayname = "th";
var year = currentTime.getFullYear();
alert(monthname+" "+day+""+dayname+" "+ year);
$('[name=DateDynamic]').text(monthname+", "+day+""+dayname+" "+ year);
</script>

Related

want to display consecutive Friday date for Saturday and Sunday. and from Monday is use current date

i am taking date from server and need to display on html page .
date will change every day . but on saturday sunday will show friday date .
again from next monday it will regular date please help`
i am taking span for display .
getServerTime is for requesting server date.
HTML:
<span id="currentdate"></span>
JavaScript:
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
var allmonth = new Array(12);
allmonth[0] = "january";
allmonth[1] = "february";
allmonth[2] = "march";
allmonth[3] = "april";
allmonth[4] = "may";
allmonth[5] = "june";
allmonth[6] = "july";
allmonth[7] = "august";
allmonth[8] = "september";
allmonth[9] = "october";
allmonth[10] = "november";
allmonth[11] = "december";
function getServerTime() {
return $.ajax({
async: false
}).getResponseHeader('Date');
}
var st = getServerTime();
var date = new Date(st);
//alert(date+"this is server date");
var day = weekday[date.getDay()];
var currentdate = date.getDate();
var currentmonth = allmonth[date.getMonth()];
var currentyear = date.getFullYear();
var fulldate = currentdate + "-" + currentmonth + "-" + currentyear;
var fridayday = "";
if (day == 'Monday' || day == 'Tuesday' || day == 'Thursday' ||
day == 'Wednesday') {
$("#currentdate").html(fulldate);
alert("this is working day");
} else if (day == "Friday") {
fridayday = fulldate;
alert("this is friday");
alert(fridayday + "fridayday date inside if");
$("#currentdate").html(fulldate);
} else if (day == 'Saturday' || day == 'Sunday') {
$("#currentdate").html(fridayday);
alert("this is not a working day");
}
alert(fridayday + "fridayday date out side if");
From what i understood through reading your question, you want to display on days Friday, Saturday and Sunday the same thing. So why dont you implement Saturday and Sunday in your else if statement ?
i.e.:
else if (day == "Friday" || day == "Saturday" || day == "Sunday") {
fridayday = fulldate;
alert("this is " + day);
alert(fridayday + "fridayday date inside if");
$("#currentdate").html(fulldate);
}

javascript print weekend date

Hello Guys i want to show the week ending date in javascript or through some jquery calendar plugin with below functionality
It looks something like this:
Week Ending: < show weekending date in dd/MMM/YYYY format >
and then if we click on these left and right arrows it should show next weekend in same format.
kindly please suggest me if there is a plugin with similar functionality or if we can achieve this with simple javascript
Use this to get the first and last day of week.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
console.log("Week Start : "+firstday);
console.log("Weekend : "+lastday);
var date = new Date(lastday);
var formattedDate = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
console.log(formattedDate);
You can change lastday format manually using getDay(), getMonth() and getFullYear()
Try This .
var current = new Date(); // get current date
var weekstart = current.getDate() - current.getDay() +1;
var weekend = weekstart + 6; // end day is the first day + 6
var monday = new Date(current.setDate(weekstart));
var sunday = new Date(current.setDate(weekend));
<html>
<head>
<script>
function myFunction(data) {
if(data == "down")
change = change - 7;
else if(data == "up")
change = change + 7;
var someDate = new Date();
var day = someDate.getDay();
var numberOfDaysToAdd = 0;
if(day == 1) { numberOfDaysToAdd = 5; }
else if(day == 2) { numberOfDaysToAdd = 4; }
else if(day == 3) { numberOfDaysToAdd = 3; }
else if(day == 4) { numberOfDaysToAdd = 2; }
else if(day == 5) { numberOfDaysToAdd = 1; }
someDate.setDate(someDate.getDate() + numberOfDaysToAdd + change);
var dd1 = someDate.getDate();
var mm1 = someDate.getMonth() + 1;
var yy1 = someDate.getFullYear();
someDate.setDate(someDate.getDate() + 1);
var dd2 = someDate.getDate();
var mm2 = someDate.getMonth() + 1;
var yy2 = someDate.getFullYear();
var someFormattedDate = dd1 + '/'+ mm1 + '/'+ yy1 + '\n' + '&' +
dd2 + '/'+ mm2 + '/'+ yy2;
document.getElementById("showWeekends").innerHTML = someFormattedDate;
}
</script>
</head>
<body>
<button onclick="myFunction('down')"><</button>
<span id="showWeekends"></span>
<button onclick="myFunction('up')">></button>
</body>
<script>
var change = 0;
myFunction("none");
</script>
</html>

Javascript date validation - prefixing 19 (century) to two digit date

I am doing some validations with Date() and I have noticed that if I create a invalid date with a two digit year instead of four Date(01/01/55) then the current century will be prefixed onto the year - 55 becomes 1955 - instead of a invalid date object that I can test with NaN.
This is a problem because I allow users to enter dates without any '/', then I create the date using substr:
// Check date is in correct format
var fDate = val.split('/');
// Should have 3 parts
if (fDate.length != 3) {
var day = val.substr(0, 2);
var month = val.substr(2, 2);
var year = val.substr(4, 4);
val = day + '/' + month + '/' + year;
control.val(val);
}
So if the user enters 010155 my logic turns it into 01/01/55 then Date() creates the date 01/01/1955, but instead I want it to create an invalid date object.
Okay well I developed a solution that does what I'm happy with. momentjs.com seems great, and I probably could of used it, but I am using the jqueryui.com Datepicker which uses Date and I want the use to be able to enter dates with no year, 1 or 2 number years, which defaults to the beginning of this century.
var cYear = new Date().getFullYear();
var c = cYear.toString().substr(0, 2);
day = val.substr(0, 2);
if (day > 31) {
leftOverD = day.charAt(1);
day = "0" + day.charAt(0);
} else if (day.length == 1) {
day = "0" + day;
} else if (day.length == 0) {
day = "01";
}
month = (leftOverD) ? leftOverD + val.charAt(2) : val.substr(2, 2);
if (month > 12) {
leftOverM = month.charAt(1);
month = "0" + month.charAt(0);
} else if (month.length == 1) {
month = "0" + month;
} else if (month.length == 0) {
month = "01";
}
var strYear;
if (leftOverD && leftOverM) {
strYear = val.substr(2, 4);
} else if (leftOverD || leftOverM) {
strYear = val.substr(3, 4);
} else if (!leftOverD && !leftOverM) {
strYear = val.substr(4, 4);
}
year = strYear;
if (year.length == 0) {
year = c + "00";
} else if (year.length == 1) {
var nYear = c + '0' + year;
if (nYear > cYear)
nYear = (c - 1) + '0' + year
year = nYear;
} else if (year.length == 2) {
var nYear = c + year;
if (nYear > cYear)
nYear = (c - 1) + year
year = nYear;
}
ps. Working with dates in JS is a nightmare. Why not simply have a Date() constructor that accepts a culture?

First Tuesday of every Month

Hello I am trying to use the following code which is a mish mash of "lifted code" but it keeps pumping out todays date and time.
I am trying to get the date for the first Tuesday of every month at 19:00.
I am using W3C School Try-it for testing purposes.
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{
var myDate = new Date();
myDate.setHours(19, 00, 0, 0);
myDate.setYear(2013);
myDate.setDate(1);
myDate.setMonth();
//Find Tuesday
var tue = 2;
while(myDate.getDay() != tue) {
myDate.setDate(myDate.getDate() + 1);
}
document.write(myDate);
</script>
</head>
<body>
<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>
Roy
<==Update==>
I have use your code which works well but need to factor in after the First Tuesday has happened for the next month, I have tried this if statement but breaks.
function getTuesday() {
var datenow = new Date();
var d = new Date(),
month = d.getMonth(),
tuedays= [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 2) {
d.setDate(d.getDate() + 1);
}
// Get all the other Tuesdays in the month
while (d.getMonth() === month) {
tuedays.push(new Date(d.setHours(17,00,00,00)));
d.setDate(d.getDate() + 7);
}
If (d.getDate() >= datenow.getDate)
{
d.setMonth(d.getMonth() + 1);
document.write(tuedays[1]);
}
Else
{
document.write(tuedays[1]);
}
}
Use below function, that will give you current month Tuesdays.
function getTuesday() {
var d = new Date(),
month = d.getMonth(),
tuesdays= [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 2) {
d.setDate(d.getDate() + 1);
}
// Get all the other Tuesdays in the month
while (d.getMonth() === month) {
tuesdays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return tuesdays;
}
I know that this is old but this is a function that i wrote based on what Sahal wrote that accepts a few additional features. Ill go through the arguments and returns below.
function getDates(dayString, month, year, first, allInYear) {
if (!dayString) { console.error('Missing required parameter: dayString is required.'); return; }
if (first === undefined || first === null) { first = false; }
if (allInYear === undefined || allInYear === null) { allInYear = false; }
if (year === undefined || year === null) { year = new Date().getFullYear(); }
var converted = false;
if (month === undefined || month === null) {
var temp = new Date();
if (temp.getDate() > 9) {
month = ((temp.getMonth() + 1) == 12) ? 11 : (temp.getMonth() + 1);
} else {
month = temp.getMonth();
}
converted = true;
}
if (typeof month === "string" && isNaN(parseInt(month))) {
month = month.toLowerCase().substring(0, 3);
switch (month) {
case "jan":
month = 0;
break;
case "feb":
month = 1;
break;
case "mar":
month = 2;
break;
case "apr":
month = 3;
break;
case "may":
month = 4;
break;
case "jun":
month = 5;
break;
case "jul":
month = 6;
break;
case "aug":
month = 7;
break;
case "sep":
month = 8;
break;
case "oct":
month = 9;
break;
case "nov":
month = 10;
break;
case "dec":
month = 11;
break;
default:
var temp = new Date();
if (temp.getDate() > 9) {
month = ((temp.getMonth() + 1) == 12) ? 11 : (temp.getMonth() + 1);
} else {
month = temp.getMonth();
}
converted = true;
break;
}
} else if (typeof month === "number" || (typeof month === "string" && !isNaN(parseInt(month)))) {
month = (!converted) ? parseInt(month) - 1 : month;
}
if (typeof year === "string" && !isNaN(parseInt(year)) || typeof year === "number") {
if (parseInt(year) / 1000 > 2) {
year = parseInt(year);
} else if (parseInt(year) / 10 >= 0 && parseInt(year) / 10 < 10) {
var temp2 = new Date().getFullYear();
year = (parseInt(Math.floor(temp2 / 100)) * 100) + parseInt(year);
}
} else if (typeof year === "string" && isNaN(parseInt(year))) {
if (year === "this") {
year = new Date().getFullYear();
} else if (year === "last") {
year = new Date().getFullYear() - 1;
} else if (year === "next") {
year = new Date().getFullYear() + 1;
} else {
console.warn('Year string not recognized, falling back to current year. (this, last, next).');
year = new Date().getFullYear();
}
}
var dates = [];
//hang in there this is going to get a doosie
var d = new Date(),
dow = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"],
getDow = function(sd, dowa) {
for (var i = 0; i < dowa.length; i++) {
var day = dowa[i];
if (sd.toLowerCase().substring(0, 3) == day) {
return i;
}
}
return -1;
},
di = getDow(dayString, dow),
getDIM = function(year, mon) {
var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mon];
};
d.setFullYear(year);
d.setMonth(month, 1);
if (di == -1) { console.error('Range Error: Day of the week should be between sunday and saturday'); return; }
if (first && !allInYear) {
while (d.getDay() !== di) {
d.setDate(d.getDate() + 1);
}
return d;
} else if (first && allInYear) {
var tm = 0;
d.setMonth(tm, 1);
for (var i = tm; i <= 11; i++) {
while (d.getDay() !== di) {
d.setDate(d.getDate() + 1);
}
dates.push(new Date(d));
tm += 1;
d.setMonth(tm, 1);
}
return dates;
} else if (!first && !allInYear) {
var eom = getDIM(d.getFullYear(), d.getMonth());
for (var x = 1; x <= eom; x++) {
if (d.getDay() === di) {
dates.push(new Date(d));
}
d.setDate(d.getDate() + 1);
}
return dates;
} else if (!first && allInYear) {
var tm = 0;
for (var i = 0; i <= 11; i++) {
var eom = getDIM(d.getFullYear(), i),
dim = [];
d.setMonth(i, 1);
for (var x = 1; x <= eom && d.getMonth() == i; x++) {
if (d.getDay() === di) {
dim.push(new Date(d));
}
d.setDate(d.getDate() + 1);
}
dates.push(dim);
}
return dates;
} else {
return [];
}
}
So the only required argument is the day string, optionally you can set month,year,first or all in a month and all in a year or not, month and year default to current, and first and allInYear default to false, But you can set first in moth, by passing null or undefined to the month and year parameter.
month parameter accepts: null|undefined, number, or string eg 'July'
year parameter accepts: null|undefined, number 2 or 4 digit, string eg '19' or '2019' also 'last', 'this', 'next'
returns Date object,Array[Date object...], or Array[Array[Date object...]...]
This has been tested and should cover most situations...
Well, it's been over 8 years since I asked this question, and it showed up at the top result on Google for 'The first Tuesday of every month'. The original project is dead now, but I've gained more experience, I feel better placed to provide an answer.
First thing to note, is the original question wasn't obvious, and the title was just as ambiguous. The original goal, was to get the next occurrence of a first Tuesday of the month, so could be the current month, or next month depending on where you are in the month.
Because of the ambiguity in the question, I have tried to cover for those differences in interpretation in the answer.
My first function, is to get the occurrence of a specific day of the week for a given month and year. Thank you to #Amadan in the comments on one of the answers.
function GetFirstDayOfMonth(dayOfTheWeek, month, year){
const date = new Date(year, month, 1);
date.setDate(date.getDate() + ((7 + dayOfTheWeek) - date.getDay()) % 7)
return date;
}
The next function, gets the next occurrence of a first specified day of the week given a date.
function GetFirstNextFirstDayOfTheWeek(currentDate, day){
const returnValue = GetFirstDayOfMonth(day, currentDate.getMonth(), currentDate.getFullYear());
if(returnValue.getDate() < currentDate.getDate()){
return GetFirstNextFirstDayOfTheWeek(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1), day);
}
return returnValue;
}
So to achieve the original question I can run the following example
const tuesday = 2;
function GetFirstNextFirstTuesday(){
return GetFirstNextFirstDayOfTheWeek(new Date(), tuesday);
}
To achieve getting the first Tuesday of a Month
const tuesday = 2;
function GetFirstTuesday(month, year){
return GetFirstDayOfMonth(tuesday, month, year);
}
And to finish getting all the first Tuesdays of a given year.
const tuesday = 2;
function GetFirstTuesdayOfEveryMonth(year){
const dates = [];
for (let index = 0; index < 12; index++) {
dates.push(GetFirstDayOfMonth(tuesday, index, year));
}
return dates;
}
function GetFirstDayOfMonth(dayOfTheWeek, month, year){
// Get the first day of the month
const date = new Date(year, month, 1);
// Set the date based on the day of the week.
date.setDate(date.getDate() + ((7 + dayOfTheWeek) - date.getDay()) % 7)
return date;
}
function GetFirstNextFirstDayOfTheWeek(currentDate, day){
const returnValue = GetFirstDayOfMonth(day, currentDate.getMonth(), currentDate.getFullYear());
if(returnValue.getDate() < currentDate.getDate()){
return GetFirstNextFirstDayOfTheWeek(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1), day);
}
return returnValue;
}
const tuesday = 2;
function GetFirstTuesday(month, year){
return GetFirstDayOfMonth(tuesday, month, year);
}
function GetFirstNextFirstTuesday(){
return GetFirstNextFirstDayOfTheWeek(new Date(), tuesday);
}
function GetFirstTuesdayOfEveryMonth(year){
const dates = [];
for (let index = 0; index < 12; index++) {
dates.push(GetFirstDayOfMonth(tuesday, index, year));
}
return dates;
}
console.log(GetFirstNextFirstTuesday());
console.log(GetFirstTuesday(09, 2021));
console.log(GetFirstTuesdayOfEveryMonth(2022));
Hopefully, this can help anyone who may seem to stubble on this old post, and thank you to the people that did answer.

JavaScript time compare

I have now the following code:
var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_time = curr_hour + ":" + curr_minute;
var open_time = "17:00";
if(Date.parse ( curr_time ) > Date.parse ( open_time )){
alert("Webshop is open");
} else {
alert("Webshop is closed.");
}
What the code should do is.. if the current time is greater then 17:00 send the alert and if not, send the other alert.. All i get now is that it is closed.
You don't need all that parsing, you already know getHours() method!
if(new Date().getHours() >= 17)
...that's it!
You can't just parse time in hh:mm format. Give it an arbitrary date (Jan 1, 2012 in this case) to make it a full date object. The date doesn't matter as long as it's the same for both.
if(Date.parse('01/01/2012 ' + curr_time) > Date.parse ('01/01/2012 ' + open_time)){
console.log("open");
}else{
console.log("closed");
}
A simpler approach would be to just compare the hours and minutes since that's what you have.
curr_hour > open_hour && curr_minute > open_minute
Why create date objects? Just use basic math.
var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_time = curr_hour + curr_minute/60;
var open_time = 17;
var openClosed = curr_time > open_time ? "Open" : "Closed";
alert("Webshop is " + openClosed + ".");
Try this:
var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_second = d.getSeconds();
if((curr_hour > 17) || (curr_hour == 17 && curr_minute == 0 && curr_second == 0 )){
alert("Webshop is open");
} else {
alert("Webshop is closed.");
}

Categories