In epoch
1265997351408
is
Fri Feb 12 2010 12:55:51 GMT-0500 (EST)
I am trying to write it as:
February, 12 2010
But I am getting: November, 10 42087
What am I doing wrong?
function makeHumanDate(epoch) {
var theDate = epoch * 1000
var months = new Array(13);
months[0] = "January";
months[1] = "February";
months[2] = "March";
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 d = new Date(theDate);
var monthnumber = d.getUTCMonth();
var monthname = months[monthnumber];
var monthday = d.getUTCDate();
var year = d.getFullYear();
if(year < 2000) { year = year + 1900; }
var dateString = monthname +
', ' +
monthday +
' ' +
year;
// Goal is: February, 12 2010
return dateString;
}
I know its something dumb but I've been stuck for a while. Please Help.
Thanks!
You don't need to multiply epoch by 1000 in your example code - if you take this out, it works as expected :)
A little code clean-up
function makeHumanDate(epoch) {
var months = ["January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"],
d = new Date(epoch),
month = months[d.getUTCMonth()],
day = d.getUTCDate(),
year = d.getFullYear();
// not needed as getFullYear returns the full year in 4 digits
//if( year < 2000 ) year += 1900;
return month + ', ' + day + ' ' + year;
}
Your code is fine but your input is broken. If I use http://www.onlineconversion.com/unix_time.htm
I get the same result you do.
Your timestamp seems to need a division by 1000 to get it back into a reasonable frame, after which I get the correct result.
Related
This is the date input
<input id="customer-date" name="customer-date" type="date" required>
and this is the script
const customerDate = document.getElementById('customer-date').value;
const dateHandler = document.getElementById('date-handler');
dateHandler.innerHTML = customerDate;
But when I pick a date, the value I get to display in dateHandler is formatted like 2017-11-22 the problem is that the format="dd/MM/yyyy" attribute doesn't make it consistent between days and months when displaying and its obviously confusing. So I want to get the month name from the picked date to display it such 2017-November-22. Any ideas?
If you were looking to just get the month name from the month number, you could use this:
var str = "2017-11-22"; // this would be your date
var res = str.split("-"); // turn the date into a list format (Split by / if needed)
var months = ["Jan", "Feb", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
console.log(months[res[1]-1]) // month name
JSFiddle: https://jsfiddle.net/p8fwhydc/1/
When reformatting a date string, you should always consider just reformatting the string and avoiding Date objects altogether, as for Noy's answer.
However, you can also use some Date object features if you take precautions to avoid the pitfalls of parsing and formatting.
This type of question is two questions in one:
How do I parse the string to a Date
How do I format the date
In the first case, a date format of YYYY-MM-DD should be parsed as UTC (some browsers may not) so you should parse that manually.
The second part is to generate a formatted string, you can leverage the Intl object where supported to get the string in the host default language, e.g.
// Parse string in YYYY-MM-DD format as local
function parseYMD(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
// Format Date as D-MMMM-YYYY using host default language for month name
function formatDMMMMY(date) {
function z(n){return (n<10?'0':'') + n}
return date.getFullYear() + '-' +
date.toLocaleString(undefined, {month:'long'}) + '-' +
z(date.getDate());
}
var s = '2017-11-22';
console.log(parseYMD(s).toString());
console.log(formatDMMMMY(parseYMD(s)));
You can use the Date() javascript function like :
Date.prototype.getFullDate = function() {
return this.getFullYear() + '-' + this.toLocaleString(undefined, {month:'long'}) + '-' + this.getDate();
}
const dateStr = document.getElementById('customer-date').value.split('/');
var date = new Date(dateStr[2], dateStr[1], dateStr[0]);
document.getElementById('date-handler').innerHTML = date.getFullDate();
Here's the simple solution I made , I hope that helps you
function showdate() {
var customerDate = document.getElementById('customer-date').value;
var dateHandler = document.getElementById('date-handler');
dateHandler.innerHTML = customerDate;
var months = new Array();
months[0] = "January";
months[1] = "February";
months[2] = "March";
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 date = new Date(customerDate);
var month = months[date.getMonth()];
//converting the date into array
var dateArr = customerDate.split("-");
//setting up the new date form
var forDate = dateArr[0] + "-" + month + "-" + dateArr[2];
document.getElementById("new-date-handler").innerHTML = forDate;
}
<input id="customer-date" name="customer-date" type="date" required>
<input type=button value=validate onclick="showdate()">
<p id="date-handler"></p>
<p id="new-date-handler"></p>
could you please tell me how to convert date one formate to another in javascript ?
var date = new Date("24 May 2017, 05:35");
d=date.getDate();
m=date.getMonth();
y=date.getYear();
h=date.getHours();
m=date.getMinutes();
console.log(m +' '+d +' '+y+', ' + h+m)
// expected output
//May 24, 2017, 05.35 AM IST
https://jsfiddle.net/bbbnxfz8/
I don't want to use any library like moment
For example if you have
var date = new Date("24 May 2017, 05:35");
var day1 = date.getDate();
You can convert like this -->
var date2 = new Date(date);
var day = date2.getDay();
You can pass a object always content a date form
Do you like this?
As you stated the problem, I had a solution, tweak it as you want.
Also try this Fiddle DEMO
function dateFormater(dateStr, format, separator) {
var date = new Date(dateStr),
formatArr = format.split('-'),
len = formatArr.length,
str = '',
i,
monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
getdata = function(d) {
function getCurrentTime(d) {
var currentTime,
hour = d.getHours(),
meridiem = hour >= 12 ? "PM" : "AM";
return ((hour + 11) % 12 + 1) + ":" + d.getMinutes() + ' ' + meridiem;
}
switch (d) {
case 'day':
return getDay(date.getDay);
case 'month':
return monthNames[date.getMonth()];
case 'dd':
return date.getDate();
case 'mm':
return date.getMonth();
case 'yy':
return date.getFullYear();
case 'time':
return getCurrentTime(date);
case 'zone':
return date.toString().match(/\(([A-Za-z\s].*)\)/)[1];
}
},
getDay = function(d) {
switch (d) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
};
for (i = 0; i < len; i++) {
i === len - 1 && (separator = '');
str += getdata(formatArr[i]) + separator;
}
return str;
}
var format = 'month-dd-yy-time-zone';
console.log(dateFormater("24 May 2017, 05:35", format, ', ')); // May, 24, 2017, 5:35 AM, IST
// Creating Date object
var date = new Date("24 May 2017, 05:35");
// fetching date
d = date.getDate();
// fetching month
m = date.getMonth();
// fetching year
y = date.getFullYear();
// fetching hours
h = date.getHours();
// fetching minutes
min= date.getMinutes();
// creating month's name array to display name of month
var monthArr = new Array();
monthArr = ['Jan','Feb','March','April','May']; // you can add all months
// Code to show time as per requirement
var ampm = h >= 12 ? 'pm' : 'am';
h = h % 12;
hours = h ? h : 12; // the hour '0' should be '12'
minutes = min < 10 ? '0'+min : min;
var strTime = hours + '.' + minutes + ' ' + ampm;
var finalDate = monthArr[m]+' '+d+','+y+', '+strTime;
console.log(finalDate);
I hope this helps you.
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
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();
I want to print something like this (a 7-day calendar) but with the ability to start from any date I want.
Monday, 1 January 2011
Tuesday, 2 January 2011
Wednesday, 3 January 2011
Thursday, 4 January 2011
Friday, 5 January 2011
Saturday, 6 January 2011
Sunday, 7 January 2011
So for example I want to show next seven days from 22 of February. Have no idea how to handle this.
This seems to be what you're looking for:
function GetDates(startDate, daysToAdd) {
var aryDates = [];
for (var i = 0; i <= daysToAdd; i++) {
var currentDate = new Date();
currentDate.setDate(startDate.getDate() + i);
aryDates.push(DayAsString(currentDate.getDay()) + ", " + currentDate.getDate() + " " + MonthAsString(currentDate.getMonth()) + " " + currentDate.getFullYear());
}
return aryDates;
}
function MonthAsString(monthIndex) {
var d = new Date();
var month = new Array();
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";
return month[monthIndex];
}
function DayAsString(dayIndex) {
var weekdays = new Array(7);
weekdays[0] = "Sunday";
weekdays[1] = "Monday";
weekdays[2] = "Tuesday";
weekdays[3] = "Wednesday";
weekdays[4] = "Thursday";
weekdays[5] = "Friday";
weekdays[6] = "Saturday";
return weekdays[dayIndex];
}
var startDate = new Date();
var aryDates = GetDates(startDate, 7);
console.log(aryDates);
Result (as of today):
["Thursday, 5 April 2012",
"Friday, 6 April 2012",
"Saturday, 7 April 2012",
"Sunday, 8 April 2012",
"Monday, 9 April 2012",
"Tuesday, 10 April 2012",
"Wednesday, 11 April 2012",
"Thursday, 12 April 2012"]
Here's a working fiddle.
Here is my solution using Moment.js
Next 7 days
let days = [];
let daysRequired = 7
for (let i = 1; i <= daysRequired; i++) {
days.push( moment().add(i, 'days').format('dddd, Do MMMM YYYY') )
}
console.log(days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Just in case if you need previous 7 days
let days = [];
let daysRequired = 7
for (let i = daysRequired; i >= 1; i--) {
days.push( moment().subtract(i, 'days').format('dddd, Do MMMM YYYY') )
}
console.log(days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
An initial date:
var startingDay = new Date(year, month, day);
A whole week from startingDay:
var thisDay = new Date();
for(var i=0; i<7; i++) {
thisDay.setDate(startingDay.getDate() + i);
console.log(thisDay.format());
}
The formatting function:
Date.prototype.format = function(){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
return days[this.getDay()]
+", "
+this.getDate()
+" "
+months[this.getMonth()]
+" "
+this.getFullYear();
};
var feb22 = new Date(2012, 1, 22);
var feb23 = new Date(feb22.getTime() + 1000*60*60*24);
...and so on
You can set the variable dateString to whatever you want and in the loop you just increase the day.
Then you will get the dates, but I think in a different format.
var dateString = '22 Feb 2012';
var actualDate = new Date(dateString);
var newDate;
for(var i=1; i<=7; i++){
newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+i);
}
If you need next 7 weekdays starting from today
const isWeekday = (date) => {
return date.weekday()!==0 && date.weekday()!==6
}
const weekdays=[];
let numberOfDaysRequired = 7
let addDaysBy = 1
moment.locale('en')
while(weekdays.length < numberOfDaysRequired)
{
const d = moment().add(addDaysBy, 'days')
if(isWeekday(d))
{
weekdays.push(d.format('dddd, Do MMMM YYYY'))
}
addDaysBy++;
}
console.log(weekdays)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>