Javascript: Date Issue - javascript

I create a new Date in javascript and provide it the string value of a date like so:
>>> string_date = '2009-09-09';
>>> var myDate = new Date(string_date);
>>> myDate
Tue Sep 08 2009 20:00:00 GMT-0400 (EST) { locale="en"}
The string date comes from a calendar picker widget and I write the value from that widget to a hidden input field. The format of the date is YYYY-MM-DD. Also, with the code above, I write the date selected to a div to show the date in a nice way. However, the users are confused by the date shown that way. So, how can I show the date in such a way that the locale is not considered and so, write it as Sep 09, 2009?
Thanks! :)

Something like this?
<script type="text/javascript">
<!--
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(m_names[curr_month] + " " + curr_date + ", " + curr_year);
//-->
</script>
More here: http://www.webdevelopersnotes.com/tips/html/javascript_date_and_time.php3

myDate.toDateString()
If you don't want the day, (1 + myDate.getMonth()) + ' ' + myDate.getDate() + ', ' + myDate.getFullYear().
If you don't need that comma, you can write that as [1 + myDate.getMonth(), myDate.getDate(), myDate.getFullYear()].join(' ')
Edit: Forgot that getMonth() doesn't return human-readable names, and that you'd have to store them in an array as per #NinjaCat.

var parts = myDate.split(' ');
var strDate = parts[1] + ' ' + parts[2] + ', ' + part[3]
If you go the "correct" way and use getXXX remember that getMonth() needs +1 since JS months start at 0.

Related

Javascript Countdown Date

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 });
});

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.

How to parse date field from json using angularJs filter

Here is what i'm getting from json file /Date(1435837792000+0000)/
I need to display date in the following format Oct 29, 2010 9:10:23 AM
There is no function like format() on the Date prototype in Javascript. But there are these methods:
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
getHours() // Returns the hour
getMinutes() // Returns the minute
getSeconds() // Returns the second
You can form the string yourself using:
function formatDate(dt) {
var monthNames = ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
var h = dt.getHours(), am;
if (h > 12) {
am = 'pm';
h = h - 12;
} else {
am = 'am';
}
return monthNames[dt.getMonth()].substring(0, 3) + ' ' +
dt.getDate() + ', ' + dt.getFullYear() + ' ' +
h + ':' + dt.getMinutes() + ':' + dt.getSeconds() + ' ' +
am;
}
console.log(formatDate(new Date(1435837792000+0000)));
If you are finding yourselves in need of more date parsing and formatting, check out the Momentjs library. With moment, you could just do:
moment(new Date(1435837792000+0000)).format("MMM D, YYYY hh:mm:ss A")
Use JS to convert it to Date object & then date function on it..
<html>
<head>
<script>
function jsonDatetoJSDate(){
var dateFromServer = "/Date(1435837792000+0000)/";
//Javascript conversion
var prsdDt = new Date(parseInt(dateFromServer.substr(6)));
//getting Date Object
var uDate = new Date(prsdDt);
alert(uDate);
}
</script>
</head>
<body onload="javascript:jsonDatetoJSDate()">
Use Date Function on javaScript
</body>
</html>
As you mentioned in comments, if the JSON you are getting is something like
var obj = {
"PublishDate": "\/Date(1435757849000+0000)\/"
}
and you have no control in changing the value(since you are enclosing the Date() around slashes), then you would need to
escape the slashs around Date.
obj.PublishDate.replace(/\//g, "");
and evaluate the remaining expression
eval(obj.PublishDate.replace(/\//g, ""))
to get the actual Date: Wed Jul 08 2015 11:48
You can extract this value from your json.
Assign it to a scope variable in the controller.
yourCtrl.js
json = { name: 'stackoverflow',
date: 1435837792000+0000
};
$scope.today = new Date(json.date); //This converts the date value from the json to a healthy looking date something like this `2015-07-02T11:49:52.000Z`
today.html
{{ today | date:'medium' }}
This angular filter will display your date in the desired date format.
Oct 29, 2010 9:10:23 AM
EDIT:
$scope.today = Date(1435837792000+0000);
$scope.today = new Date($scope.today);
and then pipe it up as using the angular filters as follows
{{ today | date:'MMM d, y hh:mm:ss' }} or {{ today | date:'medium' }} based upon your requirement.
First get the timestamp from JSON to a Date variable, here’s a brute match:
var json = { "PublishDate": "\/Date(1435757849000+0000)\/" };
var timestamp = parseInt(json.PublishDate.match(/\d+/)[0],10);
var date = new Date(timestamp);
Then, a mix of .toDateString() and .toLocaleTimeString(), both quirky (yet localized) and possibly unreliable non-standard, might come close:
date = date.toDateString() + ' ' + date.toLocaleTimeString('en');
alert( date === 'Wed Jul 01 2015 3:37:29 PM' );
There’s also .toGMTString() that returns Thu, 02 Jul 2015 11:49:52 GMT (RFC 1123) respectively.

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