How to get nth Weekday of Current date in javascript - javascript

I need to retrieve nth weekday of the current date in js. like 1st Sunday, 2nd Sunday
var d=new Date();
var weekDay=d.getDay();
here weekDay gives me 4 that means its Wednesday(3rd Wednesday). So far its good.
from weekDay i can say that its wednesday.
how to calcuate the "3rd" index of this wednesday?
Thank you

What du you actually mean? To get the dates you could use Date(). Like for instance creating a variable "today" and setting it to be todays date.
var today = new Date();
In a greater context you could go as far as showing everything from weekdays, date, year etc etc! I'll provide a code bit below. The code shows a dynamic clock/date in HTML.
You can format this the way you want, and choose which variables to show! This is btw the same code as found here: Other thread/question
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today=new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = "Date: " + day + "/" + month + "/" + year + " " + "Clock: " + h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Is this what you mean?

Something like this
function getNth(dat) {
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday'],
nth = ['st', 'nd', 'rd', 'th', 'th'],
d = dat ? dat instanceof Date ? dat : new Date(dat) : new Date(),
date = d.getDate(),
day = d.getDay(),
n = Math.ceil(date / 7);
return n + nth[n-1] + ' ' + days[day];
}
document.body.innerHTML = '' +
'today ....: ' + getNth() + '<br>' +
'1/31/2015 : ' + getNth('1/31/2015') + '<br>' +
'1/16/2015 : ' + getNth('1/16/2015');
body {font-family: monospace}

As per my understanding you want what date will be 1st, 2nd sunday/Monday from today. If it is that then you can use this
//consider sun=o,mon=1,....,sat:6
function getWeekday(n,day)
{
var today = new Date();
var presentDay = today.getDay();
var presentTime = today.getTime();
if(day < presentDay)
{
day = day +6;
}
var diff = day - present day;
var daysAfter = (n-1)*7 + diff;
var timeAfter = presentTime+daysAfter*86400000;
var next date = new Date(timeAfter);
}
// if you want to get 1st sunday from today just call this
var sunday1 = getWeekday(1,0)
// to get second monday from today
var monday2 = getWeekday(2,1)

Related

How would I fix this function to change month depending on the date?

I'm trying to create a function that creates a dynamic date range based on the date supplied in a string.
What I've done so far:
Capture date in the string I'm looking to change;
Check to see if that date is a Thursday (if so the range will need to account for the weekend)
What I need to do:
Find a way to get the second date in the range to account for the weekend;
Find a way to make sure that the second date takes into account the last day of the month.
Apologies for old syntax, GTM doesn't like anything using ES6 so I'm a little constrained on this project.
Note I am using DD/MM/YYYY
var regex = /[\d\/\d\/\d]/g;
var text = document.querySelector('.shipmentLineTitle b');
var originalDate = text.innerText.match(regex, "");
if (originalDate.length > 10) {
originalDate.pop();
originalDate.join('');
}
var ogDateString = originalDate.join('');
var dayNumber = originalDate.splice(0, 2).join('');
var monthNumber = originalDate.splice(1, 2).join('');
var yearNumber = originalDate.splice(2, 4).join('');
// if originalDate is a thursday (5) dynamicString will need to be a Monday (1).
var date = new Date(yearNumber, monthNumber -1, dayNumber);
var dynamicDateString = "";
if (date.getDay == 5) {
var newDate = new Date(date) + (86400000 * 3);
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dymamicDateString = dd + '/' + mm + '/' + yy;
} else {
var newDate = new Date(date) + 86400000;
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dynamicDateString = dd + '/' + mm + '/' + yy;
}
var newContent = 'Delivery will be made between ' + ogDateString + ' - ' + dynamicDateString + '. An accurate delivery date will be provided after you place your order.';
text.innerText = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 09/10/2020 (1 delivery)</b></span>
Thursday is day 4
Here is a simpler script
var textField = document.querySelector('.shipmentLineTitle b'),
text = textField.innerText,
originalDate = text.match(/\d{2}\/\d{2}\/\d{4}/)[0].split("/"),
dayNumber = +originalDate[0],
monthNumber = +originalDate[1],
yearNumber = +originalDate[2],
date = new Date(yearNumber, monthNumber - 1, dayNumber, 15, 0, 0, 0),
aDay = 86400000,
newDate = new Date(date),
day = date.getDay(),
daysToAdd = 1; // Sunday to Wednesday
// if originalDate is a Thursday (4) or Saturday (6), dynamicString will need to be a Monday (1).
if (day === 4) daysToAdd = 4; // Thursday - delivery Monday
else if (day === 6) daysToAdd = 2; // Saturday
newDate.setDate(newDate.getDate() + daysToAdd);
var dd = newDate.getDate(),
mm = newDate.getMonth() + 1,
yy = newDate.getFullYear(),
dynamicDateString = dd + '/' + mm + '/' + yy,
newContent = text + ' - ' + dynamicDateString + '</b>. An accurate delivery date will be provided after you place your order.';
textField.innerHTML = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 08/10/2020 (1 delivery)</b></span>
I would suggest to user moment.js a very good date library to manipulate dates. It has lot of function to add/substract dates, hours, days etc.
There is https://www.npmjs.com/package/moment-business-days which servers exactly what you need

Get current date in DD-Mon-YYY format in Jquery [duplicate]

How can I format the date using jQuery. I am using below code but getting error:
$("#txtDate").val($.format.date(new Date(), 'dd M yy'));
Please suggest a solution.
add jquery ui plugin in your page.
$("#txtDate").val($.datepicker.formatDate('dd M yy', new Date()));
jQuery dateFormat is a separate plugin. You need to load that explicitly using a <script> tag.
An alternative would be simple js date() function, if you don't want to use jQuery/jQuery plugin:
e.g.:
var formattedDate = new Date("yourUnformattedOriginalDate");
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
m += 1; // JavaScript months are 0-11
var y = formattedDate.getFullYear();
$("#txtDate").val(d + "." + m + "." + y);
see: 10 ways to format time and date using JavaScript
If you want to add leading zeros to day/month, this is a perfect example:
Javascript add leading zeroes to date
and if you want to add time with leading zeros try this:
getMinutes() 0-9 - how to with two numbers?
Here's a really basic function I just made that doesn't require any external plugins:
$.date = function(dateObject) {
var d = new Date(dateObject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = day + "/" + month + "/" + year;
return date;
};
Use:
$.date(yourDateObject);
Result:
dd/mm/yyyy
I'm using Moment JS. Is very helpful and easy to use.
var date = moment(); //Get the current date
date.format("YYYY-MM-DD"); //2014-07-10
ThulasiRam, I prefer your suggestion. It works well for me in a slightly different syntax/context:
var dt_to = $.datepicker.formatDate('yy-mm-dd', new Date());
If you decide to utilize datepicker from JQuery UI, make sure you use proper references in your document's < head > section:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
I hope this code will fix your problem.
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
curr_month++ ; // In js, first month is 0, not 1
year_2d = curr_year.toString().substring(2, 4)
$("#txtDate").val(curr_day + " " + curr_month + " " + year_2d)
Add this function to your <script></script> and call from where ever you want in that <script></script>
<script>
function GetNow(){
var currentdate = new Date();
var datetime = currentdate.getDate() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
return datetime;
}
window.alert(GetNow());
</script>
or you may simply use the Jquery which provides formatting facilities also:-
window.alert(Date.parse(new Date()).toString('yyyy-MM-dd H:i:s'));
I love the second option. It resolves all issues in one go.
If you are using jquery ui then you may use it like below, you can specify your own date format
$.datepicker.formatDate( "D dd-M-yy", new Date()) // Output "Fri 08-Sep-2017"
Just use this:
var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);
Though this question was asked a few years ago, a jQuery plugin isn't required anymore provided the date value in question is a string with format mm/dd/yyyy (like when using a date-picker);
var birthdateVal = $('#birthdate').val();
//birthdateVal: 11/8/2014
var birthdate = new Date(birthdateVal);
//birthdate: Sat Nov 08 2014 00:00:00 GMT-0500 (Eastern Standard Time)
You can add new user jQuery function 'getDate'
JSFiddle: getDate jQuery
Or you can run code snippet. Just press "Run code snippet" button below this post.
// Create user jQuery function 'getDate'
(function( $ ){
$.fn.getDate = function(format) {
var gDate = new Date();
var mDate = {
'S': gDate.getSeconds(),
'M': gDate.getMinutes(),
'H': gDate.getHours(),
'd': gDate.getDate(),
'm': gDate.getMonth() + 1,
'y': gDate.getFullYear(),
}
// Apply format and add leading zeroes
return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});
return getDate(str);
};
})( jQuery );
// Usage: example #1. Write to '#date' div
$('#date').html($().getDate("y-m-d H:M:S"));
// Usage: ex2. Simple clock. Write to '#clock' div
function clock(){
$('#clock').html($().getDate("H:M:S, m/d/y"))
}
clock();
setInterval(clock, 1000); // One second
// Usage: ex3. Simple clock 2. Write to '#clock2' div
function clock2(){
var format = 'H:M:S'; // Date format
var updateInterval = 1000; // 1 second
var clock2Div = $('#clock2'); // Get div
var currentTime = $().getDate(format); // Get time
clock2Div.html(currentTime); // Write to div
setTimeout(clock2, updateInterval); // Set timer 1 second
}
// Run clock2
clock2();
// Just for fun
// Usage: ex4. Simple clock 3. Write to '#clock3' span
function clock3(){
var formatHM = 'H:M:'; // Hours, minutes
var formatS = 'S'; // Seconds
var updateInterval = 1000; // 1 second
var clock3SpanHM = $('#clock3HM'); // Get span HM
var clock3SpanS = $('#clock3S'); // Get span S
var currentHM = $().getDate(formatHM); // Get time H:M
var currentS = $().getDate(formatS); // Get seconds
clock3SpanHM.html(currentHM); // Write to div
clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span
setTimeout(clock3, updateInterval); // Set timer 1 second
}
// Run clock2
clock3();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="date"></div><br>
<div id="clock"></div><br>
<span id="clock3HM"></span><span id="clock3S"></span>
Enjoy!
You could make use of this snippet
$('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1900:+0',
defaultDate: '01 JAN 1900',
buttonImage: "http://www.theplazaclub.com/club/images/calendar/outlook_calendar.gif",
dateFormat: 'dd/mm/yy',
onSelect: function() {
$('#datepicker').val($(this).datepicker({
dateFormat: 'dd/mm/yy'
}).val());
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
selector: <input type="text" class="datepicker">
</p>
<p>
output: <input type="text" id="datepicker">
</p>
Simply we can format the date like,
var month = date.getMonth() + 1;
var day = date.getDate();
var date1 = (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + date.getFullYear();
$("#txtDate").val($.datepicker.formatDate('dd/mm/yy', new Date(date1)));
Where "date" is a date in any format.
Take a look here:
https://github.com/mbitto/jquery.i18Now
This jQuery plugin helps you to format and translate date and time according to your preference.
Use dateFormat option when creating date picker.
$("#startDate").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy/mm/dd'
});
you can use the below code without the plugin.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$( function() {
//call the function on page load
$( "#datepicker" ).datepicker();
//set the date format here
$( "#datepicker" ).datepicker("option" , "dateFormat", "dd-mm-yy");
// you also can use
// yy-mm-dd
// d M, y
// d MM, y
// DD, d MM, yy
// &apos;day&apos; d &apos;of&apos; MM &apos;in the year&apos; yy (With text - 'day' d 'of' MM 'in the year' yy)
} );
</script>
Pick the Date: <input type="text" id="datepicker">
You can try http://www.datejs.com/
$('#idInput').val( Date.parse("Jun 18, 2017 7:00:00 PM").toString('yyyy-MM-dd'));
BR
This worked for me with slight modification and without any plugin
Input : Wed Apr 11 2018 00:00:00 GMT+0000
$.date = function(orginaldate) {
var date = new Date(orginaldate);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = month + "/" + day + "/" + year;
return date;
};
$.date('Wed Apr 11 2018 00:00:00 GMT+0000')
Output: 04/11/2018
I have achieved through this, I have resolved this without any plugin or datepicker.
GetDatePattern("MM/dd/yyyy");
function GetDatePattern(pattern)
{
var monthNames=["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var todayDate = new Date();
var date = todayDate.getDate().toString();
var month = todayDate.getMonth().toString();
var year = todayDate.getFullYear().toString();
var formattedMonth = (todayDate.getMonth() < 10) ? "0" + month : month;
var formattedDay = (todayDate.getDate() < 10) ? "0" + date : date;
var result = "";
switch (pattern) {
case "M/d/yyyy":
formattedMonth = formattedMonth.indexOf("0") == 0 ? formattedMonth.substring(1, 2) : formattedMonth;
formattedDay = formattedDay.indexOf("0") == 0 ? formattedDay.substring(1, 2) : formattedDay;
result = formattedMonth + '/' + formattedDay + '/' + year;
break;
case "M/d/yy":
formattedMonth = formattedMonth.indexOf("0") == 0 ? formattedMonth.substring(1, 2) : formattedMonth;
formattedDay = formattedDay.indexOf("0") == 0 ? formattedDay.substring(1, 2) : formattedDay;
result = formattedMonth + '/' + formattedDay + '/' + year.substr(2);
break;
case "MM/dd/yy":
result = formattedMonth + '/' + formattedDay + '/' + year.substr(2);
break;
case "MM/dd/yyyy":
result = formattedMonth + '/' + formattedDay + '/' + year;
break;
case "yy/MM/dd":
result = year.substr(2) + '/' + formattedMonth + '/' + formattedDay;
break;
case "yyyy-MM-dd":
result = year + '-' + formattedMonth + '-' + formattedDay;
break;
case "dd-MMM-yy":
result = formattedDay + '-' + monthNames[todayDate.getMonth()].substr(3) + '-' + year.substr(2);
break;
case "MMMM d, yyyy":
result = todayDate.toLocaleDateString("en-us", { day: 'numeric', month: 'long', year: 'numeric' });
break;
}
}
I'm not quite sure if I'm allowed to answer a question that was asked like 2 years ago as this is my first answer on stackoverflow but, here's my solution;
If you once retrieved the date from your MySQL database, split it and then use the splitted values.
$(document).ready(function () {
var datefrommysql = $('.date-from-mysql').attr("date");
var arraydate = datefrommysql.split('.');
var yearfirstdigit = arraydate[2][2];
var yearlastdigit = arraydate[2][3];
var day = arraydate[0];
var month = arraydate[1];
$('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);
});
Here's a fiddle.
Here is the full code example I have show on browser, Hope you also helpful thanks.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker" ).datepicker({
minDate: -100,
maxDate: "+0D",
dateFormat: 'yy-dd-mm',
onSelect: function(datetext){
$(this).val(datetext);
},
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type="text" id="datepicker"></p>
</body>
</html>
using Moment JS
moment js
$("#YourDateInput").val(moment($("#YourDateInput").val()).format('YYYY-MM-DD'));
u can use this coding
$('[name="tgllahir"]').val($.datepicker.formatDate('dd-mm-yy', new Date(data.tgllahir)));

javascript date of specific day of the week in MM/dd/yyyy format not libraries

I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:
Sun Dec 22 2013 16:39:49 GMT-0500 (EST)
but I would like it in this format 12/22/2013 -- MM/dd/yyyy
Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}
I have code that gives me the correct format but that is of the current date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
this prints:
>>> 12/23/2013
when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy
How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?
You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
Complete example:
var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013
To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:
function setToPreviousWeekday(date, weekday) {
var current_weekday = date.getDay();
// >= always gives you the previous day of the week
// > gives you the previous day of the week unless the current is that day
if (current_weekday >= weekday) {
current_weekday += 6;
}
date.setDate(date.getDate() - (current_weekday - weekday));
}
To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:
currentTime.setDate(currentTime.getDate() + (7 - currentTime.getDay()));
Subtract days like this
// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);
var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Here is my suggestion. Create a function like so... in order to format any date you send it.
function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}
Now, to print the current date, you can use this code here:
var today = new Date();
var todayFormatted = formatDate(today);
To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...
var prevSunday = today;
while (prevSunday.getDay() !== 0) {
prevSunday.setDate(prevSunday.getDate()-1);
}
var sundayFormatted = formatDate(prevSunday);
To see the whole thing together, take a look at this DEMO I've created...
** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.
You can create prototype functions on Date to do what you want:
Date.prototype.addDays = function (days) {
var d = new Date(this.valueOf());
d.setDate(d.getDate() + days);
return d;
}
Date.prototype.getMostRecentPastSunday = function () {
var d = new Date(this.valueOf());
return d.addDays(-d.getDay()); //Sunday is zero
}
Date.prototype.formatDate = function () {
var d = new Date(this.valueOf());
//format as you see fit
//http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
//using your approach...
var month = d.getMonth() + 1
var day = d.getDate()
var year = d.getFullYear()
return month + "/" + day + "/" + year;
}
console.log((new Date()).getMostRecentPastSunday().formatDate());
console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());
//or...
var d = new Date(); //whatever date you want...
console.log(d.getMostRecentPastSunday().formatDate());
Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.
The logging at the bottom shows you how this works for 100 days into the future.
var dateHelper = {
getPreviousSunday: function (date) {
var millisInADay = 86400000;
if (!date.getDate()) {
console.log("not a date: " + date);
return null;
}
date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
}
}
var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
var nextDate = new Date(now + i * 86400000);
console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}

JavaScript : displaying Yesterdays Date in JavaScript

I was trying to display Yesterday Date on click of the button , but why its showing Date as "2013-6-0"
instead of 2013-05-31
Could anybody please tell me what i was doing wrong
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{
var d = new Date();
var curr_date = d.getDate()-1;
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var yesterday = curr_year + "-" + curr_month + "-" + curr_date ;
document.write(yesterday);
}
</script>
</head>
<body>
<p id="demo">Click Button to Display Yesterday Date</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>
You should update and then reference the date from which you've subtracted 1 day:
var d = new Date();
d.setDate(d.getDate() - 1); // <-- add this to make it "yesterday"
var curr_date = d.getDate(); // <-- don't subtract 1 anymore
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
DEMO
Your code simply takes a day number (like 1, 2, ...) and subtracts one from it. Why would you expect that to automatically roll the day back to the previous month?
You can generate new dates by subtracting milliseconds from a given date. Try this:
var today = new Date();
# subtract milliseconds representing one day from current date
var yesterday = new Date(today - 24*60*60*1000);
var today = new Date();
var yesterday = new Date();
yesterday.setDate(today.getDate()-1);
var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate();
function displayDate()
{
var today = new Date();
today.setDate(today.getDate()-1);
var yyyy = today.getFullYear().toString();
var mm = (today.getMonth()+1).toString();
mm = mm.length==2?mm:"0"+mm;
var dd = today.getDate().toString();
dd = dd.length==2?dd:"0"+dd;
var yesterday = yyyy+"-"+mm+"-"+dd;
document.write(yesterday);
}

Getting current date and time in JavaScript

I have a script that prints the current date and time in JavaScript, but the DATE is always wrong. Here is the code:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33
.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.
So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:
.getDate() returns the day of the month <- this is the one you want
.getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc
so your code should look like this:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances
You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
You can then simply retrieve the date and time by doing the following:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " # " + newDate.timeNow();
Or call the method inline so it would simply be -
var datetime = "LastSync: " + new Date().today() + " # " + new Date().timeNow();
To get time and date you should use
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
To get only the date you should use
new Date().toLocaleDateString();
>> "09/08/2014"
To get only the time you should use
new Date().toLocaleTimeString();
>> "2:35:56 AM"
Or if you just want the time in the format hh:mm without AM/PM for US English
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
or for British English
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Read more here.
For true mysql style output use this function below: 2019/02/28 15:33:12
If you click the 'Run code snippet' button below
It will show you an simple realtime digital clock example
The demo will appear below the code snippet.
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
<div id="digital-clock"></div>
Just use:
var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
Short
I develop Steve answer to get exactly what OP need
new Date().toLocaleString().replace(',','')
console.log(new Date().toLocaleString().replace(',',''));
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Change .getDay() method to .GetDate() and add one to month, because it counts months from 0.
This should do the trick:
function dateToString(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
dateOfString += date.getFullYear();
return dateOfString;
}
var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Basic JS (good to learn): we use the Date() function and do all that we need to show the date and day in our custom format.
var myDate = new Date();
let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec'];
let date = myDate.getDate();
let month = monthsList[myDate.getMonth()];
let year = myDate.getFullYear();
let day = daysList[myDate.getDay()];
let today = `${date} ${month} ${year}, ${day}`;
let amOrPm;
let twelveHours = function (){
if(myDate.getHours() > 12)
{
amOrPm = 'PM';
let twentyFourHourTime = myDate.getHours();
let conversion = twentyFourHourTime - 12;
return `${conversion}`
}else {
amOrPm = 'AM';
return `${myDate.getHours()}`}
};
let hours = twelveHours();
let minutes = myDate.getMinutes();
let currentTime = `${hours}:${minutes} ${amOrPm}`;
console.log(today + ' ' + currentTime);
Node JS (quick & easy): Install the npm pagckage using (npm install date-and-time), then run the below.
let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
Short and simple:-
console.log(new Date().toLocaleString());
Reference
I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;
getDay() gets the day of the week. 3 is Wednesday. You want getDate(), that will return 18.
Also getMonth() starts at 0, you need to add 1 to get 4 (April).
DEMO: http://jsfiddle.net/4zVxp/
You need to use getDate() to get the date part. The getDay() function returns the day number (Sunday = 0, Monday = 1...), and the getMonth() returns a 0 based index, so you need to increment it by 1.
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+ (parseInt(currentdate.getMonth()) + 1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time
console.log(date.toLocaleString()) // For both Date and Time
For Documentation
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
get current date and time
var now = new Date();
var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
I think that makes it way easier to handle dates in javascript.
.getDay returns day of week. You need .getDate instead.
.getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.
This little code is easy and works everywhere.
<p id="dnt"></p>
<script>
document.getElementById("dnt").innerHTML = Date();
</script>
there is room to design
function UniqueDateTime(format='',language='en-US'){
//returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
//e.g : 20170428-115833-547
//allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
var dt = new Date();
var modele="YYYYMMDD-HHmmSS-mss";
if (format!==''){
modele=format;
}
modele=modele.replace("YYYY",dt.getFullYear());
modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
return modele;
}
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" +
dt.toISOString().substring(5,7)+ "/" +
dt.toISOString().substring(0,4) + " " +
dt.toTimeString().substring(0,8))
var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);
I think i am very late to share my answer, but i think it will be worth.
function __getCurrentDateTime(format){
var dt=new Date(),x,date=[];
date['d']=dt.getDate();
date['dd']=dt.getDate()>10?dt.getDate():'0'+dt.getDate();
date['m']=dt.getMonth()+1;
date['mm']=(dt.getMonth()+1)>10?(dt.getMonth()+1):'0'+(dt.getMonth()+1);
date['yyyy']=dt.getFullYear();
date['yy']=dt.getFullYear().toString().slice(-2);
date['h']=(dt.getHours()>12?dt.getHours()-12:dt.getHours());
date['hh']=dt.getHours();
date['mi']=dt.getMinutes();
date['mimi']=dt.getMinutes()<10?('0'+dt.getMinutes()):dt.getMinutes();
date['s']=dt.getSeconds();
date['ss']=dt.getSeconds()<10?('0'+dt.getSeconds()):dt.getSeconds();
date['sss']=dt.getMilliseconds();
date['ampm']=(dt.getHours()>=12?'PM':'AM');
x=format.toLowerCase();
x=x.indexOf('dd')!=-1?x.replace(/(dd)/i,date['dd']):x.replace(/(d)/i,date['d']);
x=x.indexOf('mm')!=-1?x.replace(/(mm)/i,date['mm']):x.replace(/(m)/i,date['m']);
x=x.indexOf('yyyy')!=-1?x.replace(/(yyyy)/i,date['yyyy']):x.replace(/(yy)/i,date['yy']);
x=x.indexOf('hh')!=-1?x.replace(/(hh)/i,date['hh']):x.replace(/(h)/i,date['h']);
x=x.indexOf('mimi')!=-1?x.replace(/(mimi)/i,date['mimi']):x.replace(/(mi)/i,date['mi']);
if(x.indexOf('sss')!=-1){ x=x.replace(/(sss)/i,date['sss']); }
x=x.indexOf('ss')!=-1?x.replace(/(ss)/i,date['ss']):x.replace(/(s)/i,date['s']);
if(x.indexOf('ampm')!=-1){ x=x.replace(/(ampm)/i,date['ampm']); }
return x;
}
console.log(__getCurrentDateTime()); //returns in dd-mm-yyyy HH:MM:SS
console.log(__getCurrentDateTime('dd-mm-yyyy')); //return in 05-12-2016
console.log(__getCurrentDateTime('dd/mm*yyyy')); //return in 05/12*2016
console.log(__getCurrentDateTime('hh:mimi:ss')); //return in 13:05:30
console.log(__getCurrentDateTime('h:mi:ss ampm')); //return in 1:5:30 PM
I needed to figure this out for a slate in after effects. Here's what I came up with after taking elements from a few different sources -- Formatting is MM/DD/YYYY HH:MM AM/PM
D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();
N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}
amtOfZeroes = 2;
isNeg = false;
if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{
Mo = "0" + Mo;
}
if (isNeg)
Mo = "-" + Mo;
if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho;
}
if (isNeg)
Ho = "-" + Ho;
if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min;
}
if (isNeg)
Min = "-" + Min;
T = Ho + ":" + (Min)
Mo + "/" + D.getDate() + "/" + D.getFullYear() + " " + T + " " + N
If someone is in search of function
console.log(formatAMPM());
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
return strTime = date.getMonth() + '/' + date.getDay()+'/'+date.getFullYear()+' '+ hours + ':' + minutes +':'+ seconds + " " +ampm;
}
function display_c(){
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var strcount
var currentdate = new Date();
document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
tt = display_c();
}
id = 'ct' // Replace in Your id
onload = "display_ct();" // Type inside a Body Tag
My well intended answer is to use this tiny bit of JS: https://github.com/rhroyston/clock-js
clock.now --> 1462248501241
clock.time --> 11:08 PM
clock.weekday --> monday
clock.day --> 2
clock.month --> may
clock.year --> 2016
clock.since(1462245888784) --> 44 minutes
clock.until(1462255888784) --> 2 hours
clock.what.time(1462245888784) --> 10:24 PM
clock.what.weekday(1461968554458) --> friday
clock.what.day('14622458887 84') --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458') --> 2016
clock.what.time() --> 11:11 PM
clock.what.weekday('14619685abcd') --> clock.js error : expected unix timestamp as argument
clock.unit.seconds --> 1000
clock.unit.minutes --> 60000
clock.unit.hours --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks --> 604800000
clock.unit.months --> 2628002880
clock.unit.years --> 31536000000
Its simple and superb
$(document).ready(function () {
var fpsOut = document.getElementById('myTime');
setInterval(function () {
var d = new Date();
fpsOut.innerHTML = d;
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTime"></div>
please find the below fiddler for the example
http://jsfiddle.net/4zVxp/483/
Here is my work around clock full format with day, date, year and time
and make Sure the date of your PC is set to the right date and if you are using PHP make sure in php.ini date.timezone= xx where xx your current timezone
function startTime()
{
var today=new Date();
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st','nd','rd'];
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
document.getElementById('txt').innerHTML=(weekday[today.getDay()] + ',' + " " + today.getDate()+'<sup>'+suffixes[today.getDate()]+'</sup>' + ' of' + " " + month[today.getMonth()] + " " + today.getFullYear() + ' Time Now ' + today.toLocaleTimeString());
t=setTimeout(function(){startTime()},500);
}
<style>
sup {
vertical-align: super;
font-size: smaller;
}
</style>
<html>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
This example of UK Time Zone.. set offset for specific Time Zone.
Example : for India : +05:30 , UK : +1
function realUKTime() {
// create Date object for current location
var d = new Date();
offset ='+1';
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
var s = nd.getSeconds();
var i = nd.getMinutes();
var h = nd.getHours();
var cDate = nd.getDate();
var m = nd.getUTCMonth();
var y = nd.getFullYear();
var newUkTime = nd.toDateString() + " "+ (Number(h)-1)+":"+i+':'+s
$("#realTime").html(newUkTime);
}
setInterval(realUKTime(),1000);
Output :: Mon Dec 27 2021 12:6:3
we can use :
new Date().toLocaleDateString() to fetch current date and
new Date().toLocaleTimeString() to fetch current time
Ex:
const date = new Date().toLocaleDateString();
const time = new Date().toLocaleTimeString();

Categories

Resources