How can i convert seconds into date format in Javascript - javascript

The code is as below my Start_DateVal has the selected date and from the datepicker .And i am trying to alert the date which is 8 months ahead from the selected date (Start_DateVal).
function ChangeEndDate()
{
var Start_DateVal = document.getElementById("Start_Date").value;
if(Start_DateVal!='')
{
var arr=Start_DateVal.split("-");
var day= arr[0];
var month= arr[1];
var year= arr[2];
var d = new Date(year, month, day);
var InSeconds=d.setMonth(d.getMonth() + 8);
alert(InSeconds); //Here i wanted to display in date format instead of seconds.
}
}
Problem Statement: i am getting the alert in Seconds (InSeconds) Variable .But how do i convert Seconds into DD-MM-YYYY Date Format.Please Help me Thank you.

var d = new Date(2017, 01, 12);
var date = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if(date<10){
date='0'+date;
}
if(month<10){
month='0'+month;
}
alert(date + '-' + month + '-' + year)

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

Wrong Date displayed

I have the following in an html file to display today's Date.
<p id="todays-date">
<script>
var currentDate = new Date();
var day = currentDate.getDay();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
var fullDate = day + "/" + month + "/" + year;
document.write(fullDate);
</script>
</p>
As for today being the 23rd of September 2021 23/9/2021 in Australia
the result I am getting is 4/8/2021.
Any help would be appreciated.
MiltonT.
getDay returns the current weekday and getMonth returns the current month, starting from 0
I would recommend you to take a look at the Date API docs
var currentDate = new Date();
var day = currentDate.getDate(); // Returns the day of the month (1–31) for the specified date according to local time.
var month = currentDate.getMonth() + 1; // Returns the month (0–11) in the specified date according to local time.
var year = currentDate.getFullYear();
var fullDate = day + "/" + month + "/" + year;
document.write(fullDate);
getDay gives you the day of the week, not the date. use getDate instead.
getMonth is zero-based. (january is 0, not 1). Add 1 to get the conventional one-based month.
Replace getDay with getDate, getDay returns the day of the week
0 represent Sunday and 6 represent Saturday. So 4 here in your question represent thursday
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
var fullDate = day + "/" + month + "/" + year;
document.write(fullDate);
Try this
var currentDate = new Date();
console.log(currentDate.toLocaleString('en-US'));
// 9/23/2021, 10:28:46 AM
YOu will get output in above format
Hello the mistake you did here is you fetched day instead of date.
The second mistake is months count from 0 to 11 instead of 1-12 increment by 1 will solve your problem
here is modified version of your code
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth()+1;
var year = currentDate.getFullYear();
var fullDate = day + "/" + month + "/" + year;
window.alert(fullDate);
js months calculate from 0-11 instead of 1-12

Javascript - Generate date from daynumber

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

HTML5 get date string convert to date object

I try to use html5 type="date" and get the string and convert it to Date() in JS.
var dateString = $(this).prev().val();
var date = new Date(dateString);
var day = date.getDay();
var month = date.getMonth();
var year = date.getYear();
finalDate = day + "/" + month + "/" + year;
alert(finalDate);
But the result I got is different than what I've set, I have no idea what's wrong here :
I expect to get 18/05/1991
My demo is here http://jsfiddle.net/yL1q3ygf/
getMonth() returns a number between 0 and 11. You want to use getMonth()+1.
getDay() returns the day of the week, you want to use getDate() instead.
use getUTCDate(); before making it as an object (date).
var d = new Date(dateString);
var n = d.getUTCDate();
then use n in your code. it will work
$(function(){
$('button').click(function(){
var dateString = $(this).prev().val();
var date = new Date(dateString);
var day = date.getDate(); //day is for day of week. use date
var month = date.getMonth() +1; // months are zero based
var year = date.getFullYear(); //use full year for 4 digit year
finalDate = day + "/" + month + "/" + year;
alert(finalDate);
});
});
I updated your jsfiddle script
http://jsfiddle.net/yL1q3ygf/5/

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

Categories

Resources