This is what I have in a script that is pulling events with a Google Calendar API:
var datestring2 = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
After I append this to a list it prints out in the format 12/2 while I want it to print out Friday, Dec 2.
How can I do this? I have looked into date.js but had no luck.
There is no built in function in Javascript that can do that (I presume you are after something like PHP's date() function).
You can certainly roll your own solution as other answers have suggested, but unless you are really against it, date.js is great for this.
You can use the libraries toString() function to get formatted date strings like so:
Date.today().toString("d-MMM-yyyy");
More information can be found in the DateJS API documention.
You need something like:
var months = ['January', 'February', 'March', ...];
var ordinals = {1:'st', 21:'st', 31:'st', 2:'nd', 22:'nd', 3:'rd', 23:'rd'};
var m = startJSDate.getMonth();
var d = startJSDate.getDate();
var s = months[m] + ', ' + s + (ordinals[s] || 'th');
This article has some great examples on printing out dates in javacript
And from there you want something like this
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
sup = "rd";
}
else
{
sup = "th";
}
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
datestring2 = d_names[curr_day] + ", " + m_names[curr_month] + " " + curr_date + sup );
Will give you Thursday, December 1st
Related
I have such javascript code
alert(DATE.value);
var d = new Date(DATE.value);
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDay();
alert(month);
alert(day);
if(2012 < year < 1971 | 1 > month+1 > 12 | 0 >day > 31){
alert(errorDate);
DATE.focus();
return false;
}
take for instance: DATE.value = "11/11/1991"
when I call alert(day); it shows me 3;
when I call alert(d); it is returns me correct info.
use .getDate instead of .getDay.
The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
getDay() returns the day of the week. You can however use the getDate() method.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDay
getDay() will give you the day of the week. You are looking for getDate().
I had a similar problem. date.getMonth() returns an index ranging from 0 to 11. January is 0. If you create a new date()-object and you want to get information about a costum date not the current one you have to decrease only the month by 1.
Like this:
function getDayName () {
var year = 2016;
var month = 4;
var day = 11;
var date = new Date(year, month-1, day);
var weekday = new Array("sunday", "monday", "tuesday", "wednesday",
"thursday", "friday", "saturday");
return weekday[date.getDay()];
}
From now on you probably want to use the following below functions for Date objects:
function dayOf(date)
{
return date.getDate();
}
function monthOf(date)
{
return date.getMonth() + 1;
}
function yearOf(date)
{
return date.getYear() + 1900;
}
function weekDayOf(date)
{
return date.getDay() + 1;
}
var date = new Date("5/15/2020");
console.log("Day: " + dayOf(date));
console.log("Month: " + monthOf(date));
console.log("Year: " + yearOf(date));
function formatDate(date, callback)
{
var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var day = weekday[date.getDay()];
console.log('day',day);
var d = date.getDate();
var hours = date.getHours();
ampmSwitch = (hours > 12) ? "PM" : "AM";
if (hours > 12) {
hours -= 12;
}
else if (hours === 0) {
hours = 12;
}
var m = date.getMinutes();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var month = months[date.getMonth()];
var year = date.getFullYear();
newdate = day + ', ' + month + ' ' + d + ',' + year + ' at ' + hours + ":" + m + " " + ampmSwitch
callback(newdate)
}
and call with this code
date="Fri Aug 26 2016 18:06:01 GMT+0530 (India Standard Time)"
formatDate(date,function(result){
console.log('Date=',result);
});
When you use the function .getDay(), this one consider the month's number start in 0 and not in 1, then if you use the date new Date(2021-11-04), the .getDay() function will consider the day 4 of dezember and not november...
Then, to get de day 4 of november, you need pass "2021-10-04" to the Date() class.
It may also be an issue with the technology used and the browser ES5 compatible.
I had such a problem while developing an application in react native.
return `${date.getDay()} ${month}, ${date.getFullYear()}`;
to
return `${date.getDate()} ${month}, ${date.getFullYear()}`;
I have this function, that gives the user the correct amount of buttons depending on the month. So if the user loads the page, Februari will show up, and 28 buttons aswell. If the user changes to March, there will be 31 buttons. The user is able to click on the button, and the corresponding button will be added to the mySql database. So if the user chooses Februari, and the button 3, the value in the database will say 2018-02-03. The problem is, and what I need help with, is if the user changes the month on the page, it does not change the value in the database. The month value in the database is always the current month of the year. Tried different solutions but nothing works. The value of the month is in a h2 with the id "displayingMonth".
Function:
function drawTable(daysInMonth) {
var cellsToDraw = daysInMonth;
var table = document.getElementById("table");
var dateObj = new Date();
var month = dateObj.getMonth()+1;
var day = dateObj.getDate();
var year = dateObj.getFullYear();
newdate = year + "-" + month;
table.innerHTML = "";
for (r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (c = 0; c < 31 && cellsToDraw > 0; c++) {
v = c +1;
//var newCell = document.createElement("td");
var newCell = document.createElement("input");
newCell.setAttribute("type", "radio");
newCell.setAttribute("name", "day");
newCell.setAttribute("value", newdate + "-" + v);
newRow.appendChild(newCell);
newCell.innerHTML =
cellsToDraw--;
}
}
}
to get the month displayed:
function daysInMonth(month, year) {
var days;
switch (month) {
case 1:
var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
days = leapYear ? 29 : 28;
break;
case 3:
case 5:
case 8:
case 10:
days = 30;
break;
default:
days = 31;
}
return days;
}
To get the month:
window.onload = function() {
var month = new Date();
var index = month.getMonth();
var months = ["Januari", "Februari", "March", "April", "May", "June", "July", "Augusti", "September", "October", "November", "December"];
document.getElementById("todayField").innerHTML = months[month.getMonth()];
// Draws a table for the current month
drawTable(daysInMonth(index, 2018));
}
to get the next month
function next() {
var months = ["Januari", "Februari", "March", "April", "May", "June", "July", "Augusti", "September", "October", "November", "December"];
var weeks = ["Sunday", "Monday", "Tuseday", "Wednesday", "Thursday", "Friday", "Saturday"];
var nextMonth = index + 1 > 11 ? 0 : index + 1;
index = nextMonth;
document.getElementById("displayingMonth").innerHTML = months[nextMonth];
drawTable(daysInMonth(index, 2018));
}
HTML
<input id="newCell"type="hidden"name="day" value="">
All help is appriciated!
Alright, some slight adjustments here. This is highly specific to your code, so bear with the changes. The issue lies with the use of var dateObj = new Date(); and then pulling the month from it to add to each 'day' radio input a user chooses.
Each input is using the 'current date' for that, and thus pulls the wrong month for what its passing.
Instead, you'll need to push the selected month date into the drawTable function, so it can build properly from that. And example of such would be:
function drawTable(daysInMonth,selectedMonth) {
...
// selectedMonth has the proper index for the Date() function
// setting 2018 here, because your code isnt inc years yet
var dateObj = new Date(2018, selectedMonth, 1, 0, 0, 0, 0);
...
}
window.onload = function() {
...
drawTable(daysInMonth(index, 2018), month.getMonth());
}
function next() {
// you may want to deal with looping to the next year here too
...
drawTable(daysInMonth(index, 2018), nextMonth);// nextMonth holds proper index
}
I think I should note that this passes the "month index", because new Date() takes a month index of 0 - 11. So passing it straight from a .getMonth() is the most compatible (no need to add +1 or -1 to them).
Here is also full chunk of your code with many changes applied to reduce some complexity and allow for years to roll as next month loops. There are a lot of changes in here, but mainly, it relies a lot more on the Date() object. No need for the daysInMonth() function you have.
// set as global
var showDate = new Date();
var months = ["Januari", "Februari", "March", "April", "May", "June",
"July", "Augusti", "September", "October", "November", "December"];
var weeks = ["Sunday","Monday","Tuseday","Wednesday","Thursday","Friday","Saturday"];
function drawTable(forDate) {
var daysInMonth = new Date(forDate.getFullYear(),forDate.getMonth()+1,0).getDate();
// ^^^ magic way to get number of days!
var cellsToDraw = daysInMonth;
// for a zero-padded non-index YYYY-MM prefix value:
var newdate = forDate.getFullYear() +"-"+ ("0"+ (forDate.getMonth() + 1)).slice(-2);
var table = document.getElementById("table");
table.innerHTML = "";
for (var r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (var c = 0; c < 31 && cellsToDraw > 0; c++) {
// for a zero-padded day to tack onto newdate
var day = ("0" + (c + 1)).slice(-2);
var newCell = document.createElement("input");
newCell.setAttribute("type", "radio");
newCell.setAttribute("name", "day");
newCell.setAttribute("value", newdate + "-" + day);// makes YYYY-MM-DD
newRow.appendChild(newCell);
newCell.innerHTML = '';
cellsToDraw--;
}
}
}
window.onload = function() {
document.getElementById("todayField").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
};
function next() {
if (showDate.getMonth() == 11) {
showDate.setMonth( 0 );
showDate.setFullYear( showDate.getFullYear()+1 );
} else {
showDate.setMonth( showDate.getMonth()+1 );
}
document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
}
function prev() {
if (showDate.getMonth() === 0) {
showDate.setMonth( 11 );
showDate.setFullYear( showDate.getFullYear()-1 );
} else {
showDate.setMonth( showDate.getMonth()-1 );
}
document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
}
This question already has answers here:
How do I format a Javascript Date?
(11 answers)
Closed 8 years ago.
I have a function that takes an input and converts it to a date. I would like to get the date in the format January 01, 2014. The #date comes in with the form as January 10 - January 25. I need to split these into two different dates (the start date and the end date). The #year comes in as 2014
Not very experienced with JavaScript but trying to get this to work.
Here is my script:
$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate); })
})
The script outputs something like... Thu Dec 25 2014 00:00:00 GMT-0500 (Eastern Standard Time)
I want it to show Thursday Dec 25, 2014 ( I don't need any time portion)
You could
use the methods of the Date-object: http://www.w3schools.com/jsref/jsref_obj_date.asp
use Moment.js: http://momentjs.com/. It's a js-library that provides methods for parsing, manipulating and formatting dates
use jQuery-Datepicker: http://api.jqueryui.com/datepicker/ for the whole task
This should work for what you are doing with the Moment.js library
<script>
$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var payPdStart = startDates[0] + ' '+ year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = moment(new Date(startDate)).format('MMMM DD, YYYY');
var endDate = Date.parse(payPdEnd);
myEndDates = moment(new Date(endDate)).format('MMMM DD, YYYY');
})
})
</script>
"July, 03 2014"
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
Number.prototype.pad = function() {
return (this < 10) ? ("0" + this) : this;
}
var d = new Date(),
h = monthNames[d.getMonth()] + " " + d.getDay().pad() + ", " + d.getFullYear();
Can i get DateTime string into desired format.
I want to get current Date into this format July 24th.
How can i get this format using jquery/javascript?
I know about the Jquery DateTime, but i did't find way to convert this into this July 24th format.
My code -
var CurrentDate = new Date();
CurrentDate.format("MMMM dd");
but this code always give me - July 24. How can i convert into my desired format.
Thanks for help, any help will be appreciable.
Test this in jsfiddler here http://jsfiddle.net/Pedro3M/rDW9v/4/
var currentTime = new Date();
var Month=new Array("January", "February", "March","April", "May", "June", "July", "August", "September", "October", "November", "December");
var Suffix=new Array("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th");
var day = currentTime.getDate();
var month = currentTime.getMonth();
if (day % 100 >= 11 && day % 100 <= 13)
today = day + "th";
else
today = day + Suffix[day % 10];
alert(Month[month]+" "+ today);
Use the plugin of jQuery for datetime format.
The plugin is here: jquery-dateFormat.
I may be completely wrong, but I don't know of any jQuery plugins that support adding "rd", "th" etc. to a date. A quick google didn't get me any results.
Here's some pseudo-code to get you started:
var toAppend = 'th';
var day = CurrentDate.getDate();
switch(day){
case '1':
toAppend = 'st';
break;
case '2':
toAppend = 'nd';
//Add the rest of the special cases
}
// If date is July 24
CurrentDate += toAppend;
Jquery date formatting and a little customization will do the job.
$(document).ready(function(){
var formattedDate = $.datepicker.formatDate("MM dd", new Date());
var day = $.datepicker.formatDate("dd", new Date());
day=parseInt(day);
if(day==1)
formattedDate+="st";
else if(day==2)
formattedDate+="nd";
else if(day==3)
formattedDate+="rd";
else
formattedDate+="th";
alert(formattedDate);
});
Include Jquery & Jquery UI library to get this functionality
Check JSFiddle HERE
As mentioned in this Link, You can do it by getting date separately and then combine as you wish. See the link please.
Some Code:
<script type="text/javascript">
<!--
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + m_names[curr_month]
+ "-" + curr_year);
//YOUR FORMAT : (MMMM dd)
document.write(m_names[curr_month]+ ' ' + curr_date);
/* The last two lines above have
to placed on a single line */
//-->
</script>
Be lucky
given my data is:
2011-12-31 01:00:00
what easy and quick script can I use to exctract simply: "DEC 31" ?
Create the following helper functions:
function getMonthName(d) {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[d.getMonth()];
}
function getShortMonthName(d) {
return getMonthName(d).substring(0, 3).toUpperCase();
}
And use them like this:
var s = "2011-12-31 01:00:00".split(/-|\s+|:/);
// new Date(year, month, day [, hour, minute, second, millisecond ])
var d = new Date(s[0], s[1] - 1, s[2], s[3], s[4], s[5]);
getShortMonthName(d) + " " + d.getDate();
Output:
"DEC 31"
http://www.datejs.com/ is nice for this
Using it the code would be like (tested and works)
Date.parse('2011-12-31 01:00:00').toString("MMM d"); // "Dec 31"
This solution is wonderful because datajs is a very flexible library.
This can do it. Just pass the string as a parameter to the date object and split the dateString. Concatenate and you're done :)
var n = new Date("2011-12-31 01:00:00");
var d = n.toDateString().split(" ");
var formattedDate = d[1].toUpperCase() + " " + d[2];
or optionally as a function
function getFormattedDate(dateString) {
var n = new Date(dateString);
var d = n.toDateString().split(" ");
return d[1].toUpperCase() + " " + d[2];
}
var formattedDate = getFormattedDate("2011-12-31 01:00:00"); // returns "DEC 31"
A function that would do exactly what you asked for (and nothing more):
function toMonthAndDay(dateString) {
var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
var dateParts = dateString.split(/[- ]/);
return months[+dateParts[1]] + " " + dateParts[2];
}
But, to take any date and output it in any custom format, I wrote a function that is loosely based on .Net DateTime format strings:
Date.prototype.format = function (format)
{
var MMMM = ["\u0000", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var MMM = ["\u0001", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dddd = ["\u0002", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var ddd = ["\u0003", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function ii(i, len) { var s = i + ""; len = len || 2; while (s.length < len) s = "0" + s; return s; }
var y = this.getFullYear();
format = format.replace(/yyyy+/g, y);
format = format.replace(/yy/g, y.toString().substr(2, 2));
format = format.replace(/y/g, y);
var M = this.getMonth() + 1;
format = format.replace(/MMMM+/g, MMMM[0]);
format = format.replace(/MMM/g, MMM[0]);
format = format.replace(/MM/g, ii(M));
format = format.replace(/M/g, M);
var d = this.getDate();
format = format.replace(/dddd+/g, dddd[0]);
format = format.replace(/ddd/g, ddd[0]);
format = format.replace(/dd/g, ii(d));
format = format.replace(/d/g, d);
var H = this.getHours();
format = format.replace(/HH+/g, ii(H));
format = format.replace(/H/g, H);
var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
format = format.replace(/hh+/g, ii(h));
format = format.replace(/h/g, h);
var m = this.getMinutes();
format = format.replace(/mm+/g, ii(m));
format = format.replace(/m/g, m);
var s = this.getSeconds();
format = format.replace(/ss+/g, ii(s));
format = format.replace(/s/g, s);
var f = this.getMilliseconds();
format = format.replace(/fff+/g, ii(f, 3));
f = Math.round(f / 10);
format = format.replace(/ff/g, ii(f));
f = Math.round(f / 10);
format = format.replace(/f/g, f);
var T = H < 12 ? "AM" : "PM";
format = format.replace(/TT+/g, T);
format = format.replace(/T/g, T.charAt(0));
var t = T.toLowerCase();
format = format.replace(/tt+/g, t);
format = format.replace(/t/g, t.charAt(0));
var day = this.getDay() + 1;
format = format.replace(new RegExp(dddd[0], "g"), dddd[day]);
format = format.replace(new RegExp(ddd[0], "g"), ddd[day]);
format = format.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
format = format.replace(new RegExp(MMM[0], "g"), MMM[M]);
return format;
};
Usage:
new Date("2011-12-31 01:00:00".replace(/-/g, "/")).format("MMM d"); // returns Dec 31
Note that IE doesn't recognize "2011-12-31 01:00:00" as a valid date string. You have to replace the dashes with slashes. To get DEC instead of Dec, you'd have to call .toUpperCase().
The differences from .Net custom date format strings are:
You can make AM/PM uppercase or lowercase by using TT or tt respectively
Using \ as an escape character is not (yet) implemented.
This should work:
var date = "2011-12-31 01:00:00";
var day = date.substring(8, 10);
var month = parseInt(date.substring(5, 7));
switch(month) {
case 1: month="JAN";break;
case 2: month="FEB";break;
case 3: month="MAR";break;
case 4: month="APR";break;
case 5: month="MAY";break;
case 6: month="JUN";break;
case 7: month="JUL";break;
case 8: month="AUG";break;
case 9: month="SEP";break;
case 10: month="OCT";break;
case 11: month="NOV";break;
case 12: month="DEC";break;
}
alert(month + " " + day);