Delivery Date Javascript Adapt To Exclude Weekends - javascript

I have been currently using this script
<script type="text/javascript">
var _next = new Date(new Date() * 1 + 24*60*60*1000*9);
document.write(" Your expected delivery date is " + (_next.getMonth() + 1) + "/" + _next.getDate() + "/" + _next.getFullYear());
</script>
I'm wondering how do I get it to exclude weekends if possible.

Just add hours if you like. this is a code that expects to deliver the next working day.
function myFunction() {
var d = new Date();
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 monthday = new Array(12);
monthday[0] = "01";
monthday[1] = "02";
monthday[2] = "03";
monthday[3] = "04";
monthday[4] = "05";
monthday[5] = "06";
monthday[6] = "07";
monthday[7] = "08";
monthday[8] = "09";
monthday[9] = "10";
monthday[10] = "11";
monthday[11] = "12";
if (d.getDay() > 0 && d.getDay() <= 4) {
d.setHours(d.getHours() + 24);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else if (d.getDay() == 0) {
d.setHours(d.getHours() + 48);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else {
d.setHours(d.getHours() + 72);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
}
}
myFunction()

<script type="text/javascript">
<!--
var myDate=new Date();
if ( myDate.getHours() < 12 ) // less than 12pm
{
var daystodeliver = [7,5,5,5,5,8,7][myDate.getDay()];
}
else
{
var daystodeliver = [7,7,7,7,7,9,8][myDate.getDay()];
}
myDate.setDate(myDate.getDate()+daystodeliver);
document.write(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] [myDate.getDay()]);
var dayofmonth = myDate.getDate();
suffix = ((dayofmonth < 10)||(dayofmonth > 20)) ? ['th','st','nd','rd','th','th','th','th','th','th'][dayofmonth % 10] : 'th';
document.write(' ' + dayofmonth + suffix + ' ');
document.write(['January','February','March','April','May','June','July','August','Septembe r','October','November','December'][myDate.getMonth()]);
// -->

Try this:
function deliver(inDays, startingOn){
var s, f = 0, d;
if(!inDays)inDays = 0;
s = !startingOn ? new Date : new Date(startingOn);
for(var i=0,n,t=0,l=inDays; i<l; i++,t+=86400000){
n = new Date(s.getTime()+t).getDay();
if(n === 0 || n === 6)f++;
}
d = new Date(s.getTime()+86400000*(inDays+f));
return 'Your expected delivery date is '+d.toLocaleDateString();
}
// same day delivery
console.log(deliver());
// deliver in 9 days stating today
console.log(deliver(9));
// deliver in 9 days starting on October 12, 2013 - must be a valid Date String
console.log(deliver(9, 'October 12, 2013'));
/* Note that in the last example the Date starts on the weekend, therefore same
day becomes Monday, which if you don't work weekends is the first day you
would see the order anyways.
*/
This is good to show your Client when something is delivered. Make sure you set the actual date it your database, according to where you are, using a Server Side language like PHP.
You should pay me for this since it will work even on a leap year. Ha!

Try this to get the date
I wrote a routine that you supply a date object, apply the menthod, the public holidays in a separate list is passed and any holidays / public holidays including weekends are skipped over.
Its this post
// array of ISO YYYY-MM-DD format dates
publicHolidays = {
uk:["2020-01-01","2020-04-10","2020-04-13","2020-05-08","2020-05-25",
"2020-08-03","2020-08-31","2020-12-25","2020-12-28"],
usa:["2020-01-01","2020-01-20","2020-02-14","2020-02-17","2020-04-10",
"2020-04-12","2020-05-10","2020-05-25","2020-06-21","2020-07-03",
"2020-07-04","2020-09-07","2020-10-12","2020-10-31","2020,11,11",
"2020-11-26","2020-12-25"]
}
// check if there is a match in the array
Date.prototype.isPublicHoliday = function( data ){// we check for a public holiday
if(!data) return 1;
return data.indexOf(this.toISOString().slice(0,10))>-1? 0:1;
}
// calculation of business days
Date.prototype.businessDays = function( d, holidays ){
var holidays = holidays || false, t = new Date( this ); // copy date.
while( d ){ // we loop while d is not zero...
t.setDate( t.getDate() + 1 ); // set a date and test it
switch( t.getDay() ){ // switch is used to allow easier addition of other days of the week
case 0: case 6: break;// sunday & saturday
default: // check if we are a public holiday or not
d -= t.isPublicHoliday( holidays );
}
}
return t.toISOString().slice(0,10); // just the YYY-MM-DD
}
// dummy var, could be a form field input
OrderDate = "2020-02-12";
// test with a UK holiday date
var deliveryDate = new Date(OrderDate).businessDays(7, publicHolidays.usa);
// expected output 2020-02-25
console.log("Order date: %s, Delivery date: %s",OrderDate,deliveryDate );

Related

Product shipping time counter in Javascript

I need a counter that counts values:
Days, e.g. 1, when ordering by 10:30 am, the change should be for 2 days after that time. Of course, the counter must also ignore the weekends.
So, buy on Friday at 14/10/2022 10:00, the date of dispatch should be on 17/10/2022. However, when ordering 14/10/2022 12:00, the shipping date should be on 18/10/2022.
it would be good to count down the time for submission to 10:30
function setShipDate () {
// element to write date to
var shipdate = document.getElementById("date");
// Set start date to today - end date in 2 days
var startDate = new Date();
var endDate = "", noOfDaysToAdd = 1, count = 0;
// Map numeric month to name
var month = new Array();
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
while(count < noOfDaysToAdd){
// add a day to the end date each loop
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
// only count when not a weekend
if(endDate.getDay() != 0 && endDate.getDay() != 6){
count++;
}
}
// update shipdate HTML
shipdate.innerHTML= endDate.getDate() + '.' + month[endDate.getMonth()] + '.' + endDate.getFullYear();
}
setShipDate();
Scheduled shipment: <span id = "date">
Surely it is possible to simplify this code + add this extra function mentioned above.
<today date> // today's date
<text id = "time"> // how much time I have left for the order with shipment:
<text id = "date"> // the end date according to the schedule until 10:30
var shipdate = document.getElementById("date");
let newDate = new Date();
// GET ORDER TIME
let orderHour = newDate.getHours();
let orderMinute = newDate.getMinutes();
let orderWeekDay = newDate.getDay();
// default delivery time
let deliverAfterDays = 1;
// delivery after weenkend
if (orderWeekDay == 5) {
deliverAfterDays = 3;
}
// Do deliveriy according to tomorrow's slot
if ((orderHour*60+orderMinute) > 630) {
deliverAfterDays++;
}
let deliveryDate = new Date(newDate.setDate(newDate.getDate() + deliverAfterDays));
const prefix0 = (n) => {
if (n <= 9) {
return "0"+n;
}
return n.toString();
}
shipdate.innerHTML= deliveryDate.getDate() + '.' + prefix0(deliveryDate.getMonth()) + '.' + deliveryDate.getFullYea();
I think this will solve your problem

JavaScript or Jquery - How to display last week of the month and next month's first Monday

How do you display only when it's the last week of the month (the text below).
The DATE that will be displayed here is next month's first Monday.
"Due on DD/MM/YY"
To detect if this is the last week in month you can follow this example:
https://www.javatpoint.com/calculate-current-week-number-in-javascript
To get next monday, you can call this function:
getNextMonday(){
var date = new Date();
date.setDate(date.getDate() + (1 + 7 - date.getDay()) % 7);
return date;
}
You can use the below JS Code. It will show the alert on last week of month means from last monday of month.
function Get_Last_Monday_of_Month()
{
var year = new Date().getFullYear();
var month = new Date().getMonth() + 1;
var dat = new Date(year+'/'+month+'/1');
var currentmonth = month;
var firstmonday = false;
while (currentmonth === month)
{
firstmonday = dat.getDay() === 1 || firstmonday;
dat.setDate(dat.getDate()+(firstmonday ? 7 : 1));
currentmonth = dat.getMonth()+1;
}
dat.setDate(dat.getDate()-7);
return dat;
}
function Get_Next_Coming_Monday()
{
var date = new Date();
date.setDate(date.getDate() + (1 + 7 - date.getDay()) % 7);
return date;
}
var d1 = new Date();
var d2 = Get_Last_Monday_of_Month();
var d3 = Get_Next_Coming_Monday();
if (d1.getTime() >= d2.getTime())
{
var datestring = ("0" + d3.getDate()).slice(-2) + "/" + ("0"+(d3.getMonth()+1)).slice(-2) + "/" + d3.getFullYear();
document.write ("Due on " + datestring);
}

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

validate a dropdown list to get proper date based on the option selected

- I have a dropdown List on which there are some options from which user can select one.
- Options are 1 day, 1 week, 2 weeks, 1 month and 6 months
- Now when I select option 1 day, today's date should be incremented by one and next date is shown.
- If I select 1 week, the date falling after one week should be shown.
- Now the problem is when I select an option it sometimes shows date greater than 30/31.
- I use below javacript function:
function select_duration(ddlcupon) {
var skillsSelect = document.getElementById("ddlcupon");
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
if (selectedText == "1 Day") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 1;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "1 Week") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 7;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "2 Weeks") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 14;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "1 Month") {
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "6 Months") {
var currentTime = new Date();
var month = currentTime.getMonth() + 7;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
- Can someone help me in getting a proper date?
try using this
var dt1 = new Date();
var dt2 = new Date(dt1.getTime() + (86400000 * numberOfDay) );
if your date is incremented by one day try
var dt2 = new Date(dt1.getTime() + (86400000 * 1 ) ); //so on
The problem is you're incrementing day, month and year. So, if the month is 12, you'll get 13. You could work directly with milliseconds. For example:
var d = new Date('01/31/2013'); // Thu Jan 31 2013 00:00:00 GMT-0200 (BRST)
var addDay = 1000 * 60 * 60 * 24;
var currentMs = d.getTime();
d.setTime(currentMs + addDay);
console.log(d); // Fri Feb 01 2013 00:00:00 GMT-0200 (BRST)
Date.js is a handy script for all kinds of JavaScript date manipulation.
The syntax to add n number of days to current day is
// Add 3 days to Today
Date.today().add(3).days();
In this case adds 3 days to the current date.

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