Javascript - Generate date from daynumber - javascript

Say I have the day number of the year.
How can I generate the date from that?
EX. Today's day number is 265
How can I get the output 9/23/2015?
Yesterday's day number was 264, how can I get the output of 9/22/2015?

Try like this
var year = 2015;
var date = new Date(year,0,1); // get the first date of year
var numberOfDaysToAdd=264;
date.setDate(date.getDate() + numberOfDaysToAdd); // add days to that date
console.log(date);

You may simply use Date():
var days = 265;
var now = new Date();
now.setMonth(0); // jan
now.setDate(days);
var date = 1 + now.getMonth();
var pad = function(v) {
return 10 > v ? '0' + v : v;
};
date = pad(date) + '/' + pad(now.getDate()) + '/' + now.getFullYear();
document.write(date);

Related

How to convert a date formatted (YYMMDD) as string but with 00 days?

I have a date formatted as string, eg: 240800. The date format for that string is YYMMDD. With the below code, I can convert the string to date but it doesn't always work in deducting 1 day. I need my output to be a valid date, not with 00 day. So with the date above, it should be converted and formatted to 07/31/2024.
Here's what I got so far.
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
var formattedDate = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
Working:
"240800" = 7/31/2024
All months from 4 to 12
Not Working:
"240100" = 0/31/2024 x
"240200" = 1/29/2024 x
"240300" = 2/31/2024 x
The reason is the date variable parameter in new Date() is counted as 0~11, not the general range,1~12.
So the working answer actually is wrong. It seems like being right just for July and August have 31 days.
The correct way is to firstly deduct 1 month and then calculate it. After all of the process is done, you can add 1 month in the end.
The below is working codes:
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
//deduct 1 month firstly
var month = Number(stringDate.substring(2,4))-1;
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
//add 1 month finally
var formattedDate = date.getMonth()+1 + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
formatDate('240100');
In python Assuming your string is yymmdd below function should do what you want. I am sure javascript has some module for date handling.
from datetime import datetime, timedelta
def fd(s):
d=datetime.strptime(s[:-2],'%y%m')+timedelta(days=int(s[-2:])-1)
return d.strftime('%m/%d/%Y')
Try this ..
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var d1;
if (day==="00")
{
d1 = new Date(month + '/01/20' + year);
d1.setDate(d1.getDate() -1);
//console.log("day1" + d1);
}
else
{
d1 = new Date('20' + year, month, day);
}
var formattedDate = d1.getMonth() + '/' + d1.getDate() + '/' + d1.getFullYear();
console.log(formattedDate);
}

Javascript format date

I have a date string which coming from the db as follows
/Date(1469167371657)/
Is there any way to convert this date to following format using javascript
MM/DD/YYYY HH:MM
I've searched a lot but unble to find a solution
In plain javascript you have to write your own function for string format a date, for example for your string format:
var date = new Date(1469167371657);
function stringDate(date) {
var mm = date.getMonth()+1;
mm = (mm<10?"0"+mm:mm);
var dd = date.getDate();
dd = (dd<10?"0"+dd:dd);
var hh = date.getHours();
hh = (hh<10?"0"+hh:hh);
var min = date.getMinutes();
min = (min<10?"0"+min:min);
return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min;
}
console.log(stringDate(date));
drier code version
var date = new Date(1469167371657);
function stringDate(date) {
return ("0" + (date.getMonth() + 1)).slice(-2)+'/'
+("0" + date.getDate()).slice(-2)+'/'
+date.getFullYear()+" "
+("0" + date.getHours()).slice(-2)+':'
+("0" + date.getMinutes()).slice(-2)
}
console.log(stringDate(date));
with pure js you can do the folowing
var d = new Date();
console.log(d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes())
You can use - http://momentjs.com/ and have it done like:
moment(1469167371657).format('MM/DD/YYYY HH:MM')
You can do this with the following steps:
1) convert the timestamp to a date object.
var timestamp = "/Date(1469167371657)/"; // However you want to save whatever comes from your database
timestamp = timestamp.substr(timestamp.indexOf("(")+1); // gives 1469167371657)/
timestamp = timestamp.substr(0,timestamp.indexOf(")")); // gives 1469167371657
var d = new Date(timestamp);
2) set it to your format
function leadZero(i) {if(i < 10) {return "0"+i;} return i;} // Simple function to convert 5 to 05 e.g.
var time = leadZero(d.getMonth()+1)+"/"+leadZero(d.getDate())+"/"+d.getFullYear()+" "+leadZero(d.getHours())+":"+leadZero(d.getMinutes());
alert(time);
Note: the date / timestamp you provided is too high for javascript to understand, so this example will not work correclty
I believe that number is milliseconds so to convert it to date, you would do this:
var time = new Date().getTime();
var date = new Date(time);
alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
var time=1469167371657;
var date = new Date(time);
alert(date.toString());

how to Add 1 year to startdate to get the end date in javascript

want a output like below
if Start Date is "01-03-2016" the End date should be "28-02-2017"
if Start Date is "10-04-2016" the End date should be "09-04-2017"
I tried below code
if (dat <= 31 && dat >= 1 && month <= 12 && month >= 1) {
var expiryDate = new Date(n1, month - 1, dat);
expiryDate.setFullYear(expiryDate.getFullYear() + 1);
var day = ('0' + expiryDate.getDate()).slice(-2);
var month1 = ('0' + (expiryDate.getMonth() + 1)).slice(-2);
var year = expiryDate.getFullYear();
var month = getMonthName(month1);
var wholeenddate = day + "-" + month + "-" + year;
but it's not produce desired output.Please Help to solve it.
Add 364 days to your date
For example
var d = new Date("2016-03-01");
d.setDate(d.getDate()+364); //outputs 28-02-2017
and
var d = new Date("2016-04-10");
d.setDate(d.getDate()+364); //outputs 09-04-2017
or Just add 1 year and sub 1 day.
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
Now it will match your output just the same even for leap year :)
Demo
var d = new Date("2016-03-01");
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
document.body.innerHTML += d.toString();
document.body.innerHTML += "<br>";
d = new Date("2016-04-10");
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
document.body.innerHTML += d.toString();
There's a convenient library to help with this sort of thing - moment.js (14k zipped).
var startDate = moment('01-03-2016', 'DD-MM-YYYY');
console.log(startDate.format('DD-MM-YYYY'));
var endDate = startDate.clone();
endDate.add(1, 'years').subtract('1', 'days');
console.log(endDate.format('DD-MM-YYYY'));
3 ways to do this.
// Add hours
var today = new Date();
today.setHours(today.getHours()+24*364);
// Add days
var nextyearDate = new Date();
nextyearDate.setDate(today.getDate()+364);
// More reliable way : Add year & subtract a day.. Hope this works...! Works for 01/01/2016
var nextDate = new Date();
nextDate.setYear(nextDate.getFullYear()+1);
nextDate.setDate(nextDate.getDate()-1);

javascript date of specific day of the week in MM/dd/yyyy format not libraries

I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:
Sun Dec 22 2013 16:39:49 GMT-0500 (EST)
but I would like it in this format 12/22/2013 -- MM/dd/yyyy
Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}
I have code that gives me the correct format but that is of the current date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
this prints:
>>> 12/23/2013
when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy
How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?
You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
Complete example:
var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013
To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:
function setToPreviousWeekday(date, weekday) {
var current_weekday = date.getDay();
// >= always gives you the previous day of the week
// > gives you the previous day of the week unless the current is that day
if (current_weekday >= weekday) {
current_weekday += 6;
}
date.setDate(date.getDate() - (current_weekday - weekday));
}
To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:
currentTime.setDate(currentTime.getDate() + (7 - currentTime.getDay()));
Subtract days like this
// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);
var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Here is my suggestion. Create a function like so... in order to format any date you send it.
function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}
Now, to print the current date, you can use this code here:
var today = new Date();
var todayFormatted = formatDate(today);
To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...
var prevSunday = today;
while (prevSunday.getDay() !== 0) {
prevSunday.setDate(prevSunday.getDate()-1);
}
var sundayFormatted = formatDate(prevSunday);
To see the whole thing together, take a look at this DEMO I've created...
** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.
You can create prototype functions on Date to do what you want:
Date.prototype.addDays = function (days) {
var d = new Date(this.valueOf());
d.setDate(d.getDate() + days);
return d;
}
Date.prototype.getMostRecentPastSunday = function () {
var d = new Date(this.valueOf());
return d.addDays(-d.getDay()); //Sunday is zero
}
Date.prototype.formatDate = function () {
var d = new Date(this.valueOf());
//format as you see fit
//http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
//using your approach...
var month = d.getMonth() + 1
var day = d.getDate()
var year = d.getFullYear()
return month + "/" + day + "/" + year;
}
console.log((new Date()).getMostRecentPastSunday().formatDate());
console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());
//or...
var d = new Date(); //whatever date you want...
console.log(d.getMostRecentPastSunday().formatDate());
Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.
The logging at the bottom shows you how this works for 100 days into the future.
var dateHelper = {
getPreviousSunday: function (date) {
var millisInADay = 86400000;
if (!date.getDate()) {
console.log("not a date: " + date);
return null;
}
date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
}
}
var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
var nextDate = new Date(now + i * 86400000);
console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}

JavaScript date: How to add a year to a string that contains mm/dd?

I have an string that contains month/date and I need to insert the year. The string looks like:
Last Mark:: 2/27 6:57 PM
I want to convert the string to something like:
Last Mark:: 2010/02/27 18:57
In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.
What is the best method for this?
Following from Adam's suggestion:
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
the code for adding THIS year is simple
var d = Date();
var withYear = d.getFullYear() + yourDate;
however, the logic behind considerating if it should be this year or last year could be harder to do
I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()
This returns the current year:
var d = new Date();
var year = d.getFullYear();
To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.
To get the day and month from the Date object:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)

Categories

Resources