How can I convert an string like "20150415" to a date with format "2015, April, 15th"? I have read several examples but they all involve a split with "-" or "/", but those don't apply to my case.
Here's my current code:
var d = parseInt(document.getElementById('date').value);
d = new Date(d[4], d[2] - 1, d[2]);
document.getElementById('date').value = d;
Any help would be much appreciated.
It seems you have a string of the form "YYYYMMDD". To get the individual parts, you just have to extract the substrings. One way would be to use a regular expression:
> "20150415".match(/(\d{4})(\d{2})(\d{2})/)
["20150415", "2015", "04", "15"]
Then you can pass the individual parts (year, month, day) to the Date constructor.
However, note that JavaScript doesn't have built-in support for formatting dates. For that you may want to use a library. See Where can I find documentation on formatting a date in JavaScript?
Here is a date formatter that takes the string '20150415' and returns the string 'April 4, 2015'. You can adjust the date format to your liking by modifying the last line of DateFormat.toLong.
var DateFormat = {
months: ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'],
toLong: function toLongDate(s) { // s is a string like '20150415'
var year = parseInt(s.substring(0, 4), 10),
month = DateFormat.months[parseInt(s.substring(4, 6), 10) - 1],
day = parseInt(s.substring(6), 10);
return month + ' ' + day + ', ' + year;
}
};
// A small test.
alert(DateFormat.toLong('20150415'));
Note that I am passing the second argument to parseInt to indicate that the number represented by the string is in base 10. If you don't specify base 10, strings starting with the numeral 0 may be parsed as though they were in base 8.
You can read about this in the JavaScript documentation on the Mozilla Developer Network:
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
Try this:
var months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
var fmt = function(str) {
var arr = str.match(/^(\d{4})(\d{2})(\d{2})$/);
arr.splice(0, 1);
arr[1] = months[+(arr[1]) - 1];
return arr.join(", ");
};
alert(fmt('20150412'));//"2015, April, 12"
although the solution of #"Felix Kling" is better, I propose a simple solution:
var d = "20150415";
//Extract 4 first letters and convert to integer, similarly with month and day
var year = parseInt(d.substr(0,4));
//subtract one since the index of the months begin in zero (january=0)
var month = parseInt(d.substr(4,2))-1;
var day = parseInt(d.substr(6,2));
d = new Date(year, month, day); // d store expected result
Related
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 1 year ago.
How do I can set the date format to "June 10, 2021"?
I have a small piece of code like this:
var homnay = new Date();
var datehomnay = (homnay.getMonth()+1) + ' ' + homnay.getDate() + ', ' + homnay.getFullYear();
document.getElementById("curDay").innerHTML = datehomnay;
Use this procedure
const MONTHS = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER']
const date = new Date()
const dateString = `${MONTHS[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`
console.log(dateString)
I am building a weather app using HTML, CSS and JavaScript.
I have succeed in displaying my current time but no luck displaying local time of the input city.
here is what it looks like:
Can I perhaps us getTimeZoneOffset() somewhere? I don't seem to figure out
function displaytheResults (weather) {
let now = new Date();
let date = document.querySelector('.location .date')
date.innerText = dateBuilder(now);
}
function dateBuilder(dt) {
let months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
let days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday']
let date = dt.getDate();
let year = dt.getFullYear();
let day = days[dt.getDay()];
let month = months[dt.getMonth()]
return `${day} ${date} ${month} ${year}`;
}
Once you have the offset value, pass it into this function, in order to get the time in the desired city:
function dateBuilder(city, offset) {
var date = new Date();
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * offset));
return `The local time in ${city} is ${newDate.toLocaleString()}`
}
I want to do something like this, I tried multiple ways but I am unable to find it. I am getting start and end date but not the current month. I want current month so it works with all locale
if(CURRENT MONTH){
// Do This
}
use the Date object for get month as follows,
var date = new Date(); // assume date is 10/06/2020
var month = date.getMonth(); // it return month as 10
if you want to get month name, firstly you should declare the array including with months and then get the month name using this array as follows,
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var date = new Date(); // assume date is 10/06/2020
var nameOfMonth = months[date.getMonth()-1] // it return month name as October
then you can use month or nameOfMonth as follows,
if (month == 10){
// Do This
}
if (nameOfMonth == 'October'){
// Do This
}
This question already has answers here:
How to get current date in jQuery?
(32 answers)
Closed 6 years ago.
How can I get the current date in JQuery as a variable and then append to a heading in with an id of currentdate, with the format 24th July 2016?
In XClass library , just do :
new Date().format('ddS mmmm yyyy')
dd : day of month
S : suffix (st,nd,th,..)
mmmm: Full name of month
yyyy : year
DEMO
var out=document.getElementById('out');
out.innerHTML=new Date().format('ddS mmmm yyyy');
<script src="https://rawgit.com/abdennour/xclass/master/node_modules/x-date/index.js"></script>
<span id="out"></span>
You need to use javascript Date() object and method of it to getting current date and component of it.
var monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var date = new Date();
var dateStr = date.getDate() + "th " + monthName[date.getMonth()] + " " + date.getFullYear();
$("#currentdate").text(dateStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="currentdate"></div>
Say I'm given a date, from which I can get its day of the month and day of the week. For example (in Javascript):
var d = new Date(1316038581772); // Wed Sep 14 2011 12:16:21 GMT-1000
var dayOfWeek = d.getDay(); // 3 - Wednesday
var dayOfMonth = d.getDate(); // 14 - Day of month
I'm looking for a value n such that this date is the nth day of the week in the month. In this case, I'm looking for n=2, for the 2nd Wednesday in September 2011.
The naive algorithm would be to find the first occurrence of that weekday in the month, take the difference in days, and divide by 7, but this isn't in constant time. For example, I would need to iterate over each day from the first day in September 7 times to reach the first Wednesday.
Is there a constant-time solution to this problem?
(For anyone interested, I'm trying to generate ordinal values for iCalendar recurrence rules; given a date, generate the monthly recurrence for the nth day of each month. The rule for this case would be something like
RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=WE;BYSETPOS=2
or
RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=2WE
)
Divide by 7 and round up.
The 14th is always the 2nd [weekday] of the month, the 15th is always the 3rd [weekday] of the month, etc.
Take the day of the month, add 6, and divide by 7, throwing away the remainder.
You need two functions- one to get the day info, the other for the nth.
Number.prototype.nth= function(){
var n= Math.round(this), t= Math.abs(n%100), i= t%10;
if(i<4 && (t<4 || t> 20)){
switch(i){
case 1:return n+'st';
case 2:return n+'nd';
case 3:return n+'rd';
}
}
return n+'th';
}
Date.prototype.nthofMonth= function(){
var today= this.getDate(),m=this.getMonth(),
day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'][this.getDay()],
month= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'][m];
return [(m+1)+'-'+today,'the ', (Math.ceil((today)/7)).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}