Javascript Countdown Date - javascript

probably an easy question for many of you. :)
I'm trying to use the simple counter from this countdown: https://github.com/rendro/countdown and i'm stuck passing javascript variable.
Normally the end date format for this counter is:
var endDate = "June 7, 2087 15:03:25";
then in the function you pass the variable:
$('.countdown.simple').countdown({ date: endDate });
but i'm trying to get a dynamic 24h date and time and sending the output in the same original endDate format. The goal is to have a countdown purchased timer to purchase this product before the end of the day so (time now - and of the day). Unfortunately its not working.
<script type="text/javascript">
var dateNow = new Date();
var monthsArray = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var monthNow = monthsArray[dateNow.getMonth()];
var dayNow = dateNow.getDate();
var yearNow = dateNow.getFullYear();
var hourNow = dateNow.getHours();
var minNow = dateNow.getMinutes();
var secNow = dateNow.getSeconds();
var completeDate = monthNow + " " + dayNow + ", " + yearNow + " " + hourNow + ":" + minNow + ":" + secNow;
$(function() {
$('.countdown.simple').countdown({ date: completeDate });
});
alert(completeDate);
</script>
i have set an alert to test the output format and its working well. But my counter is showing 0 years, 0 days, 00 hours, 00 min and 00 sec.
whats wrong..

You are setting the end date for the countdown timer to the present date. You need to pass in a future date.
Instead of creating a date string, you can also just pass in a date object.
Example
// Create the date object
var completeDate = new Date();
// Set the date to the last possible second of the day
completeDate.setHours(23, 59, 59);
// Start the timer
$(function() {
$('.countdown.simple').countdown({ date: completeDate });
});

Related

I'd like to display a string with location, date & time (of a pre-set timezone) [duplicate]

This question already has answers here:
How to make a display of a clock synchronous with the real time
(3 answers)
How do I format a date in JavaScript?
(68 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 3 years ago.
What I'd like to achieve should look like this in the bottom corner. However, I'd like to set a timezone, e.g. New York (that's not a timezone I know lol, but you understand) and it should display 'New York April 1st 05:42'.
Use this
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
setInterval(function(){
var now = new Date();
var time = monthNames[now.getMonth()] + " " + now.getDate() + ", " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
document.getElementById("currentTime").innerHTML = time;
}, 1000);
document.getElementById("name").innerHTML = Intl.DateTimeFormat().resolvedOptions().timeZone + ", ";
<p id="time"><span id="name"></span> <span id="currentTime"></span></p>
// get a new date (locale machine date time)
var date = new Date();
// First converting to UTC and then adding +360 to make it +5 GMT
const millisecondsOffset = ((date.getTimezoneOffset() + 360 ) * 60 * 1000);
date.setTime(date.getTime() - millisecondsOffset);
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = 'Islamabad, Karachi'+ ' ' + n + ' ' + time;
<div id='time'></div>

Javascript get month range by month name

I have a jQuery onclick function which basically receives a month name, and from that month name, I would like to get a month range. Like for instance I'm passing a month name "May" like this:
$('#swiperNext').click(function(e)
{
var currentMonth = $('.swiper-slide-active h3').html();
console.log(currentMonth);
});
Now I'd like to pass the current month name to a JS function and get date range for that month.
So for example May would be => 01-05-2016 - 31-05-2016, so on and so on... Can someone help me out with this ?
You can do it without any third party library like this.
I presume you are calculation for current year
var date = new Date();
var y = date.getFullYear();
var month = $('.swiper-slide-active h3').text();
var m = new Date(Date.parse(month, 1, " + y)).getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
EDIT: I have changed the answer to use a month name as a string
I would use Moment.js. It is perfect for manipulating dates and do all sorts of things.
In your specific case:
var startOfMonth = moment().month("June").startOf("month").toDate()
var endOfMonth = moment().month("June").endOf("month").toDate()
You can use this function:
function getMonthFromString(monthName){
var date = new Date(Date.parse(monthName + 1, new Date().getFullYear()));
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1).getDate();
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
var month = new Date(Date.parse(monthName + 1, new Date().getFullYear())).getMonth()+1;
var year = new Date().getFullYear();
return firstDay + "-" + month + "-" + year + " - " + lastDay + "-" + month + "-" + year;
}
First I create month name array according as getMonth() index.Then find wanted month name by indexOf ,that will return your array index when found it.
Note getMonth() is only return number between 0 and 11 assume Jan to Dec
So added 1 in getMonth
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
$('#swiperNext').click(function(e)
{
var currentMonth = $('.swiper-slide-active h3').html();
var month = monthNames.indexOf(currentMonth);
var d = new Date();
var start = new Date(d.getFullYear(),month,1);
var end = new Date(d.getFullYear(),month+1,0);
var startdate = start.getDate()+"/"+(start.getMonth()+1)+"/"+start.getFullYear();
var enddate = end.getDate()+"/"+(end.getMonth()+1)+"/"+end.getFullYear();
console.log(startdate+"-"+enddate);
});

Edit JavaScript (Tomorrow's date)

I am trying to edit some JavaScript code which basically shows tomorrow's date. However for Friday and weekends (Friday, Saturday and Sunday) it should show the following Monday's date.
Here is the code I have:
var date = new Date(); // timezone
date.setDate(date.getDate() + 1); // move to tomorrow
date.setUTCHours(11,0,0,0); // set time using UTC(GMT) timezone
document.getElementById("next-shipment").textContent = date.toLocaleString();
JSFiddle
For example let say today is Tuesday, November 4, 2015. The javascript code should show "November 5, 2015"---> in this format.
On Friday, Saturday,and Sunday the code should show: Next Monday's date: November 9, 2015
The code should work all year around.
Try this:
var today = new Date(); // timezone
document.getElementById("result").innerHTML = "<br/>Today's next day is: " + FormatDate(GetNextDay(today));
function GetNextDay(date){
date.setDate(date.getDate() + 1); // move to next day.
switch(date.getDay()) {
case 0: //Sunday
case 6: //Saturday
date = GetNextDay(date);
}
return date;
}
function FormatDate(date){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
return months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
}
function TestDate(){
var date = new Date(document.getElementById("TestDate").value);
document.getElementById("result").innerHTML += "<br/>Selected day's next day is: " + FormatDate(GetNextDay(date));
}
<input type="text" id="TestDate" value="November 06, 2015" />
<input type="button" value="Get Next Day" onclick="TestDate();" />
<div id="result"></div>
The idea is fairly simple:
The first two lines and the TestDate() function at the end are only for testing and you don't need them in your code.
The job is mainly done by the GetNextDay() function. You give it a date and it calculates and give you back the next date (skipping the weekend). It does that in two steps:
1- First it adds one day to the given date date.setDate(date.getDate() + 1);.
2- It checks the day of the new date date.getDay(). If it is 6 or 0 (Saturday or Sunday) it calls itself again date = GetNextDay(date); which means it will add one more day to the date. This concept of a function calling itself is called "recursion" in programming. When it reaches Monday, it will stop calling itself and return the date.
The only way to calculate the next day properly is by adding one day to the date. This utilizes JavaScript's Date library which knows how to do the calculation. For example, it knows that adding one day to "November 30" is "December 1", NOT "November 31". If we try to do that manually by adding 1 to number of the day: 30 + 1 = 31, but "November 31" is not a valid date. To solve this issue, we will need to write a library similar to the one that JavaScript has. Obviously, this is like reinventing the wheel and there is no point in that.
The Date constructor also has a function called getDay() which returns a integer between 0 and 6 (0 = Sunday, 6 = Saturday). You can use this to detect Friday(0), Saturday(6), Sunday(0) and omit them.
Here is a demo that alerts you if it's the weekend:
var myDate = new Date();
myDate.setFullYear(2015);
myDate.setMonth(11);
myDate.setDate(6);
if(myDate.getDate() == 5 || myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');
document.write(myDate);
To find the next day, pass the Date constructor a time & it will do the work for you. You will need to create an array however to format it in the way you want November, 5 2015.
JS:
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var tomDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = tomDate.getDate();
var month = monthNames[tomDate.getMonth()];
var year = tomDate.getFullYear()
var d = new Date();
var n = d.getDay();
if(n == 5){
var fromFri = n + 4;
document.write("<b>" + month + " " + fromFri + ", " + year + "</b>");
}else if (n == 6){
var fromSat = n + 3;
document.write("<b>" + month + " " + fromSat + ", " + year + "</b>");
}else if (n == 0) {
var fromSun = n + 2;
document.write("<b>" + month + " " + fromSun + ", " + year + "</b>");
}else{
document.write("<b>" + month + " " + day + ", " + year + "</b>");
}
Updated: CODEPEN DEMO

Parse and return components of a date using Javascript

I have a series of dates formatted similar to 2014-12-31 (year, month, day) loading into a webpage.
I'd like to use Javascript to reformat the date to appear as December 31, 2014 (month, day, year).
Is it possible to do this without splitting the string and reformatting; in other words, is it possible to only use Javascripts date() function?
For example, if I try:
d = new Date.parse('2014-12-31')
Is there a way to return only the year, month or day?
I tried d.getYear(), but that threw a "function not found" error.
Can you use momentjs.com? it's far more powerful than the default.
var yourInput = "2014-12-31";
var moment = require("moment");
var d = moment(yourInput);
var iYear = d.year();
var iMonth = d.month();
var iDay = d.day();
It is possible, but what I am showing is not very pretty, so I agree that using the well-established moment.js is a better idea. If you must not use libraries...
You have to be careful if the user is behind GMT, because creating a new Date (without a time in hours) will then be set to the previous day. getTimezoneOffset() is used to correct the desired date to midnight.
Also, you have to define an array of months to be displayed. By default, getting a month returns an integer from 0 to 11. (Jan = 0)
function myDateFormat(ymd) {
var rawDate = new Date(ymd);
var midnight = new Date(rawDate.getTime() +
rawDate.getTimezoneOffset() * 60 * 1000);
var months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
return months[midnight.getMonth()] + " " +
midnight.getDate() + ", " + midnight.getFullYear();
}
// test function
function display(x) {
document.getElementById("result").innerHTML += x + "\n";
}
display("2015-02-15 is " + myDateFormat("2015-02-15"));
display("2014-12-31 is " + myDateFormat("2014-12-31"));
display("2015-10-10 is " + myDateFormat("2015-10-10"));
<pre id="result"></pre>
You should just use var d = new Date('2014-12-31');
Date.parse returns the number of milliseconds since the Unix epoch, not a Date object.

Converting date from variable to MM-DD-YYY [duplicate]

This question already has answers here:
How do I format a Javascript Date?
(11 answers)
Closed 8 years ago.
I have a function that takes an input and converts it to a date. I would like to get the date in the format January 01, 2014. The #date comes in with the form as January 10 - January 25. I need to split these into two different dates (the start date and the end date). The #year comes in as 2014
Not very experienced with JavaScript but trying to get this to work.
Here is my script:
$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate); })
})
The script outputs something like... Thu Dec 25 2014 00:00:00 GMT-0500 (Eastern Standard Time)
I want it to show Thursday Dec 25, 2014 ( I don't need any time portion)
You could
use the methods of the Date-object: http://www.w3schools.com/jsref/jsref_obj_date.asp
use Moment.js: http://momentjs.com/. It's a js-library that provides methods for parsing, manipulating and formatting dates
use jQuery-Datepicker: http://api.jqueryui.com/datepicker/ for the whole task
This should work for what you are doing with the Moment.js library
<script>
$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var payPdStart = startDates[0] + ' '+ year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = moment(new Date(startDate)).format('MMMM DD, YYYY');
var endDate = Date.parse(payPdEnd);
myEndDates = moment(new Date(endDate)).format('MMMM DD, YYYY');
})
})
</script>
"July, 03 2014"
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
Number.prototype.pad = function() {
return (this < 10) ? ("0" + this) : this;
}
var d = new Date(),
h = monthNames[d.getMonth()] + " " + d.getDay().pad() + ", " + d.getFullYear();

Categories

Resources