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

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

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

how to get the date into string format by passing date like-01/09/2016

I want to convert Date to string format with the day name and month name like ,if am passing date like 01/09/2016 then it should be got render like day name of 1st September like Thursday 01,September 2016,the toughest task is to get day name of date.so how can i achieve this?
You can do that very easily with JavaScript. Try the following snippet:
var d = new Date("2016-09-01");
console.log(d.toDateString());
The output is:
Thu Sep 01 2016
you can try this
<script>
function myFunction() {
var s = '2016/09/01';//this may be user entered string
var d = new Date(s);
var n = d.toString();
console.log(n);
}
</script>
The format that you require dd/mm/yyyy is not natively supported you need to use something like momentjs to parse various different formats and then you can use toString as suggested
javascript native date object can be constructed from string date. But it support 'mm/dd/yyyy' format. So first convert your date format in 'mm/dd/yyyy' format. Then you can construct javascript date object. After that you can use getDay and getMonth function to get day of week and month.
function getDayOfDate (date){
var arr = date.split('/');
var newFormat=arr[1]+"/"+arr[0]+"/"+arr[2];
var date = new Date(newFormat);
return date.getDay();
}
the above function will return value from 0-6. You can use switch case to print day of week.
The following re-tunes Thursday 1 September 2016 when the following string is passed '2016-09-01'.
Please note the full name of the week Thursday is returned and not only and abbreviation like Thu;
(function() {
var dateFormat = function(ourDate) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
date = new Date(ourDate),
year = date.getFullYear(),
indexMonth = date.getMonth(),
dayWeek = date.getDay(),
day = date.getDate();
return weekDays[dayWeek] + ' ' + day + ' ' + months[indexMonth] + ' ' + year;
};
console.log(dateFormat('2016-09-01'));
})();
You can extend the datetime
Date.prototype.Format = function() {
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 weekday = weekday[this.getDay()];
var day = this.getDay();
if(day === 1)
day += day + "st"
else day+= "th"
var months = new Array(12);
months[0]= " January ";
months[1] = " February ";
months[2] = " Mars ";
months[3] = " April";
months[4] = " May ";
months[5] = " June ";
months[6] = " July ";
months[7] = " August ";
months[8] = " September ";
months[9] = " October ";
months[10] = " November ";
months[11] = " December ";
var month = months[this.getMonth()]
return weekday + day + month + this.getFullYear();
};
var d = new Date();
console.log(d.Format());
Using below code, you get date string as you mentioned.
in some cases, you get previous date than the date you entered in the var d = new Date("2016-09-01"); is due to Eastern Daylight Time.
so , this how you get exact date string format `enter code
var doo = new Date("2011-09-24");
console.log(new Date(doo.getTime() + doo.getTimezoneOffset()*60000));
here, is fiddle link : pressme

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

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.

Javascript: Date Issue

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.

Categories

Resources