javascript and jquery date format conversion - javascript

I want to convert date from this format "yyyy-MM-dd'T'HH:mm:ss.SSS"
to Mon, May 09 2016 08:12:29 using JavaScript, below code is not working. pls advice
var str2 = "2016-05-09T08:12:29.110";
var date2 = Date.parse( str2 );
alert( date2.toString( 'EEE, MMM d yyyy HH:mm:ss' ) );`

Try this:
var str2 = "2016-05-09T08:12:29.110";
var date2 = new Date(Date.parse(str2));
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
function pad(n, number) {
var str = number.toString();
var result = '';
for (var i=0; i<n-str.length; ++i) {
result += '0';
}
return result + str;
}
document.body.innerHTML = days[date2.getDay()] + ', ' + months[date2.getMonth()] + ' ' + pad(2, date2.getDate()) + ' ' + date2.getFullYear() + ' ' + pad(2, date2.getUTCHours()) + ':' + pad(2, date2.getMinutes()) + ':' + pad(2, date2.getSeconds());

Try this
var str2 = "2016-05-09T08:12:29.110";
var date2 =new Date(str2);
alert( date2 );

Related

get current date in this format "May 09, 2019"

i want to get the current time in May 09, 2019 format.
var d = new Date();
var delay = 500;
var month = d.getMonth()+1;
var day = d.getDate();
var y=d.getFullYear();
var output = d.getFullYear() + '/' +
((''+month).length<2 ? '0' : '') + month + '/' +
((''+day).length<2 ? '0' : '') + day;
here the output shows the current time in 2019/05/09 format.how should i get "May 05, 2019" format.
Try this
var d = new Date();
var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var month = months[d.getMonth()]
var day = d.getDate();
var y=d.getFullYear();
var today = month +" " +day + "," + y;
console.log(today);
Instead of creating (and maintain) your own array of names you can use the following:
d.toLocaleString('en-us', { month: 'long' });
var d = new Date();
var month = d.toLocaleString('en-us', { month: 'long' });
var day = d.getDate();
var y=d.getFullYear();
var today = month +" " +day + "," + y;
console.log(today);
You can do this,
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var d = new Date();
var day = d.getDate();
var monthIndex = d.getMonth();
var year = d.getFullYear();
var output = monthNames[monthIndex] + ' 'day + ' ,' + year;
This is exactly what you are looking for
function LogCurrentDate(e){
var date = new Date();
var options = { year: 'numeric', month: 'long', day: '2-digit' };
$(".output").empty().append("<p>" + date.toLocaleDateString('en-US', options) + "</p>");
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button onclick="LogCurrentDate(event)">Show Date</button>
</div>
<div class="output"></div>

Straight forward add days to current date javascript

I apologize as I'm sure this question has been answered already but there's so many different solutions from different years that my head is just spinning from viewing all the different solutions. But can someone please help with providing a straight forward javascript solution to display (x) days after current date?
All I'm trying to accomplish is having a notice on a page - "We are currently accepting bookings for March XX, 2017 or after" at the top.
OR is there anything I can to the code below to make it add (X) days as I'm using this to show current date.
var MONTH_NAME = ['January', 'Febuary', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
function showTime() {
function twoDigit(n) {
return ('0' + n).slice(-2);
}
function iso8601(date) {
return date.getFullYear() +
'-' + twoDigit(1 + date.getMonth()) +
'-' + twoDigit(date.getDate()) +
'T' + twoDigit(date.getHours()) +
':' + twoDigit(date.getMinutes());
}
function en_US(date) {
var h = date.getHours() % 12;
return MONTH_NAME[date.getMonth()] +
' ' + date.getDate() +
', ' + date.getFullYear();
}
var timeEl = document.getElementById('time');
if (timeEl !== null) {
var now = new Date();
timeEl.innerHTML = en_US(now);
timeDiv.setAttribute('datetime', iso8601(now));
}
};
setInterval(showTime, 1000);
Please and thank you.
You can use setDate and getDate methods to solve your problem. Take a look at addDays method I have written. Hope this helps.
var MONTH_NAME = ['January', 'Febuary', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
function showTime() {
function twoDigit(n) {
return ('0' + n).slice(-2);
}
function iso8601(date) {
return date.getFullYear() +
'-' + twoDigit(1 + date.getMonth()) +
'-' + twoDigit(date.getDate()) +
'T' + twoDigit(date.getHours()) +
':' + twoDigit(date.getMinutes());
}
function en_US(date) {
var h = date.getHours() % 12;
return MONTH_NAME[date.getMonth()] +
' ' + date.getDate() +
', ' + date.getFullYear();
}
function addDays(date, days){
var newDate = new Date(date.getTime());
newDate.setDate(newDate.getDate() + days);
return newDate;
}
var timeEl = document.getElementById('time');
if (timeEl !== null) {
var now = new Date();
timeEl.innerHTML = en_US(now) + ' to ' + en_US(addDays(now, 15));
timeEl.setAttribute('datetime', iso8601(now));
}
};
setInterval(showTime, 1000);
<div id="time"></div>

How to find ordinal position of any given weekday in JavaScript

I'm trying to find the actual position of a weekday in constant time. I get it working with loop but trying to find out it with some Mathematics. I know it is like divide it by 7 but not getting it work.
Here is the code.
for(var ind=0; ind<=between.length; ind++){
if (new Date(between[ind]).getMonthWeek() === baseDtWk && new Date(between[ind]).getDay() === baseDtD) {
datesToBeMarked.push(between[ind]);
console.log(" :Date: " + between[ind] + " :Week: " + new Date(between[ind]).getMonthWeek());
console.log("Date entered : " + new Date(between[ind]));
}
}
I have done this few days back. It is as simple as the code below. :)
On fiddle.
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(' ');
}
var date=new Date().nthofMonth();
console.log(date);
You haven't shown how you want the result to look, I guess you want to know if a particular date is, say, the nth Tuesday, e.g.
// Add ordinal to a number
function addOrdinal(n) {
var ord = [,'st','nd','rd'];
var a = n % 100;
return n + (ord[a>20? a%10 : a] || 'th');
}
// Return the ordinal number of a day in the month
function ordinalDay(d) {
d = d || new Date();
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday', 'Friday','Saturday'];
return addOrdinal(Math.ceil(d.getDate()/7)) + ' ' + days[d.getDay()];
}
console.log(ordinalDay(new Date(2015,0,1))); // 1st Thursday
console.log(ordinalDay(new Date(2015,0,27))); // 4th Tuesday
console.log(ordinalDay(new Date(2015,0,31))); // 5th Saturday
console.log(ordinalDay(new Date(2015,11,25))); // 4th Friday

javascript overwritting html buttons

I'm attempting to generate a calender using JavaScript, when i click my "Volgende" button to go to the next month my buttons get overwritten. Does anyone know how to fix this?
The HTML:
<body>
<button id="Vorige">Vorige</button> <button id="Volgende" onclick="VolgendeFunc()">Volgende</button>
<br>
<div id="div">
<script type="text/javascript" src="Kal.js"> </script>
</div>
</body>
</html>
And here the js:
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var today = new Date();
var dag = today.getDay();
var myMonth = today.getMonth();
var jaar = today.getFullYear();
function VolgendeFunc(){
myMonth = myMonth + 1;
Kalender();
}
function Kalender(){
document.write(monthNames[myMonth] + jaar + "<br>");
for (var i=1; i <= monthLength[myMonth]; i++){
document.write("<a href='#'>" + i + "</a> ");
if ( i == 7){
document.write ("<br>");
}
if ( i == 14){
document.write ("<br>");
}
if ( i == 21){
document.write ("<br>");
}
if ( i == 28){
document.write ("<br>");
}
}
}
window.onload=Kalender();
document.write immediately replaces any HTML you might have in the page.
Instead add something like a tempt var and then push HTML to that.
In a moment, I will add a jsfiddle here to show you.
Your code has some other issues...but this gets you past the first issue.
UPDATED EXAMPLE
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var today = new Date();
var dag = today.getDay();
var myMonth = today.getMonth();
var jaar = today.getFullYear();
var VolgendeFunc = function(){
myMonth = myMonth + 1;
Kalender();
}
var BackFunc = function(){
myMonth = myMonth -1;
Kalender();
}
function Kalender(){
var myHTML ='';
myHTML+=monthNames[myMonth] + jaar + "<br>";
for (var i=1; i <= monthLength[myMonth]; i++)
{
myHTML+="<a href='#'>" + i + "</a> ";
if (i%7 == 0) { myHTML += "<br>"; } //Save you some lines (best practice)
}
document.getElementById('div').innerHTML = myHTML;
}
document.addEventListener("DOMContentLoaded", Kalender, false);

Alternative to toLocaleString() for chrome browser

function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];
return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}
The above code, works well in ie browser where I get the output in the following format.
November 13,2012 10:15 AM
But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output? date.toUTCString() provides the same result but I am not sure how different it is to toLocaleString() in terms of functionality.
Thanks in advance.
Just do it manually:
// Where "date" is a Date object
function dateFormatUTC(date) {
var months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
var hours = date.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = date.getUTCMinutes();
if (hours < 10) hours = '0' + hours;
var monthName = months[date.getUTCMonth()];
var timeOfDay = hours < 12 ? 'AM' : 'PM';
return monthName + ' ' + date.getUTCDate() + ', ' +
date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
maybe you can use a thirdparty library to do stuff like that: moment.js is a good one.
Example:
moment(d).format('MMMM Do, YYYY h:mms a');
you can try using options like below:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
Please find the reference #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Categories

Resources