javascript: get month/year/day from unix timestamp - javascript

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:
function getdhm(timestamp) {
var date = Date.parse(timestamp);
var month = date.getMonth();
var day = date.getDay();
var year = date.getYear();
var formattedTime = month + '/' + day + '/' + year;
return formattedTime;
}

var date = new Date(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.

An old question, but none of the answers seemed complete, and an update for 2020:
For example: (you may have a decimal if using microsecond precision, e.g. performance.now())
let timestamp = 1586438912345.67;
And we have:
var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9
And if you'd like the month and day to always be a two-digit string (e.g. "01"):
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"
For extended completeness:
let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):
var date = new Date(parseFloat(timestamp));
or for right now:
var date = new Date(Date.now());
More info if you want it here (2017).

Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:
var date = new Date(timestamp);
Make sure your timestamp is a Number, of course.

Related

Javascript subtract one day from "yyyy-mm-ss" string IN UTC TIMEZONE

I have a string for a UTC date var latestDate='2020-11-17' , and I'm trying to get the previous days date from this string into a new variable var subtractedDate;.
So my goal is to get subtractedDate=2020-11-16
var latestDate='2020-11-17';
//convert to iso date string
var dateStr = new Date(latestDate).toISOString();
console.log('dateStr=', dateStr);
//subtract a day
//ERROR OCCURS HERE, has trouble running // var subtractedDate = dateStr.setDate(('2020-11-17T00:00:00.000Z').getDate()-1);, something with how I have '2020-11-17T00:00:00.000Z' formatted?
var subtractedDate = dateStr.setDate(dateStr.getDate()-1);
console.log('subtractedDate = ', subtractedDate);
I am trying to use ('2020-11-17T00:00:00.000Z').getDate()-1 to subtract a day from the datetimestamp but it causes an error saying Uncaught TypeError: dateStr.getDate is not a function
We should be able to use Date.parse to get the number of milliseconds since January 1, 1970, 00:00:00 UTC, then subtract 1 days worth of milliseconds (246060*1000) to get the unix time one day earlier.
We can then use Date.toLocaleTimeString to format it.
const latestDate='2020-11-17';
// Get the number of milliseconds since 1970-1-1, then subtract 1 day (24*60*60*1000 milliseconds)
const dt = new Date(Date.parse(latestDate) - 24*60*60*1000);
// Format an ISO-8601 date in the UTC timezone
const subtractedDate = dt.toLocaleDateString('sv', { timeZone: 'UTC' });
console.log({ latestDate, subtractedDate })
Please try as follows.
dateStr.setDate(dateStr.getDate()-1);
var dateStr = new Date();
var month = dateStr.getUTCMonth() + 1; //months from 1-12
var day = dateStr.getUTCDate();
var year = dateStr.getUTCFullYear();
newdate = year + "/" + month + "/" + day;

Add A Year To Today's Date

I am trying to add a year to todays date. I am working in a system that does not allow you to use standard JavaScript.
For instance, to get todays date I have to use:
javascript:now();
I have tried:
javascript:now(+1);
I have never seen this before, but am in need of adding one year to todays date...
Has anyone seen getting current date this way before? And if so, how could I add a year?
Use the Date.prototype.setFullYear method to set the year to what you want it to be.
For example:
const aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
console.log(aYearFromNow);
There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.
You can create a new date object with todays date using the following code:
var d = new Date();
console.log(d);
// => Sun Oct 11 2015 14:46:51 GMT-0700 (PDT)
If you want to create a date a specific time, you can pass the new Date constructor arguments
var d = new Date(2014);
console.log(d)
// => Wed Dec 31 1969 16:00:02 GMT-0800 (PST)
If you want to take todays date and add a year, you can first create a date object, access the relevant properties, and then use them to create a new date object
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var c = new Date(year + 1, month, day);
console.log(c);
// => Tue Oct 11 2016 00:00:00 GMT-0700 (PDT)
You can read more about the methods on the date object on MDN
Date Object
One liner as suggested here
How to determine one year from now in Javascript
by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
This code adds the amount of years required for a date.
var d = new Date();
// => Tue Oct 01 2017 00:00:00 GMT-0700 (PDT)
var amountOfYearsRequired = 2;
d.setFullYear(d.getFullYear() + amountOfYearsRequired);
// => Tue Oct 01 2019 00:00:00 GMT-0700 (PDT)
I like to keep it in a single line, you can use a self calling function for this eg:
If you want to get the timestamp of +1 year in a single line
console.log(
(d => d.setFullYear(d.getFullYear() + 1))(new Date)
)
If you want to get Date object with single line
console.log(
(d => new Date(d.getFullYear() + 1, d.getMonth(), d.getDate()))(new Date)
)
In Angular, This is how you Calculate Date
today = new Date();
year = this.today.getFullYear();
month = this.today.getMonth();
day = this.today.getDate();
//To go 18 years back
yearsBack18= new Date(this.year - 18, this.month, this.day);
//To go to same day next year
nextYear= new Date(this.year + 1, this.month, this.day);
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var fulldate = new Date(year + 1, month, day);
var toDate = fulldate.toISOString().slice(0, 10);
$("#txtToDate").val(toDate);
output : 2020-01-02
//This piece of code will handle the leap year addition as well.
function updateExpiryDate(controlID, value) {
if ( $("#ICMEffectiveDate").val() != '' &&
$("#ICMTermYears").val() != '') {
var effectiveDate = $("#ICMEffectiveDate").val();
var date = new Date(effectiveDate);
var termYears = $("#ICMTermYears").val();
date = new Date(date.setYear(date.getFullYear() + parseInt(termYears)));
var expiryDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
$('#ICMExpiryDate').val(expiryDate);
}
}
var yearsToAdd = 5;
var current = new Date().toISOString().split('T')[0];
var addedYears = Number(this.minDate.split('-')[0]) + yearsToAdd + '-12-31';

JavaScript how to get tomorrows date in format dd-mm-yy [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Incrementing a date in JavaScript
(19 answers)
How can I add 1 day to current date?
(10 answers)
Closed 12 months ago.
I am trying to get JavaScript to display tomorrows date in format (dd-mm-yyyy)
I have got this script which displays todays date in format (dd-mm-yyyy)
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
Displays: 25/2/2012 (todays date of this post)
But how do I get it to display tomorrows date in the same format i.e. 26/2/2012
I tried this:
var day = currentDate.getDate() + 1
However I could keep +1 and go over 31 obviously there are not >32 days in a month
Been searching for hours but seems to be no answer or solution around this?
This should fix it up real nice for you.
If you pass the Date constructor a time it will do the rest of the work.
24 hours 60 minutes 60 seconds 1000 milliseconds
var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
One thing to keep in mind is that this method will return the date exactly 24 hours from now, which can be inaccurate around daylight savings time.
Phil's answer work's anytime:
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);
The reason I edited my post is because I myself created a bug which came to light during DST using my old method.
The JavaScript Date class handles this for you
var d = new Date(2012, 1, 29) // month is 0-based in the Date constructor
console.log(d.toLocaleDateString())
// Wed Feb 29 2012
d.setDate(d.getDate() + 1)
console.log(d.toLocaleDateString())
// Thu Mar 01 2012
console.log(d.getDate())
// 1
Method Date.prototype.setDate() accepts even arguments outside the standard range and changes the date accordingly.
function getTomorrow() {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1); // even 32 is acceptable
return `${tomorrow.getFullYear()}/${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`;
}
Using JS only(Pure js)
Today
new Date()
//Tue Oct 06 2020 12:34:29 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0, 0))
//Tue Oct 06 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0,0)).toLocaleDateString('fr-CA')
//"2020-10-06"
Tomorrow
new Date(+new Date() + 86400000);
//Wed Oct 07 2020 12:44:02 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0, 0) + 86400000);
//Wed Oct 07 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0,0)+ 86400000).toLocaleDateString('fr-CA')
//"2020-10-07"
//don't forget the '+' before new Date()
Day after tomorrow
Just multiply by two ex:- 2*86400000
You can find all the locale shortcodes from https://stackoverflow.com/a/3191729/7877099
I would use the DateJS library. It can do exactly that.
http://www.datejs.com/
The do the following:
var d = new Date.today().addDays(1).toString("dd-mm-yyyy");
Date.today() - gives you today at midnight.
The below uses a combination of Roderick and Phil's answers with two extra conditionals that account for single digit months/days.
Many APIs I've worked with are picky about this, and require dates to have eight digits (eg '02022017'), instead of the 6 or 7 digits the date class is going to give you in some situations.
function nextDayDate() {
// get today's date then add one
var nextDay = new Date();
nextDay.setDate(nextDay.getDate() + 1);
var month = nextDay.getMonth() + 1;
var day = nextDay.getDate();
var year = nextDay.getFullYear();
if (month < 10) { month = "0" + month }
if (day < 10) { day = "0" + day }
return month + day + year;
}
Use cases :
Date.tomorrow() // 1 day next
Date.daysNext(1) // alternative Date.tomorrow()
Date.daysNext(2) // 2 days next.
IF "tomorrow " is not depend of today but of another Date different of Date.now(), Don't use static methods but rather you must use non-static :
i.e: Fri Dec 05 2008
var dec5_2008=new Date(Date.parse('2008/12/05'));
dec5_2008.tomorrow(); // 2008/12/06
dec5_2008.tomorrow().day // 6
dec5_2008.tomorrow().month // 12
dec5_2008.tomorrow().year //2008
dec5_2008.daysNext(1); // the same as previous
dec5_2008.daysNext(7) // next week :)
API :
Dateold=Date;function Date(e){var t=null;if(e){t=new Dateold(e)}else{t=new Dateold}t.day=t.getDate();t.month=t.getMonth()+1;t.year=t.getFullYear();return t}Date.prototype.daysNext=function(e){if(!e){e=0}return new Date(this.getTime()+24*60*60*1e3*e)};Date.prototype.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)};Date.prototype.tomorrow=function(){return this.daysNext(1)};Date.prototype.yesterday=function(){return this.daysAgo(1)};Date.tomorrow=function(){return Date.daysNext(1)};Date.yesterday=function(){return Date.daysAgo(1)};Date.daysNext=function(e){if(!e){e=0}return new Date((new Date).getTime()+24*60*60*1e3*e)};Date.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)}
Method 1: If you don't have problem in using other library, then this could work for you using moment.js
moment().add('days', 1).format('L');
Method 2: Using Date.js,
<script type="text/javascript" src="date.js"></script>
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy");
This method uses external library and not the native Date library.
As my bootstrap-datetimepicker was using moment.js and native date library, I preferred method 1. This question mentions these and some other methods.
Its really simple:
1: Create date object with today' date and time.
2: Use date object methods to retrieve day, month and full year and concatenate them using the + operator.
Sample Code:
var my_date = new Date();
var tomorrow_date = (my_date.getDate() + 1) + "-" + (my_date.getMonth() + 1) + "-" + my_date.getFullYear();
document.write(tomorrow_date);
function getMonday(d)
{
// var day = d.getDay();
var day = #Config.WeekStartOn
diff = d.getDate() - day + (day == 0 ? -6 : 0);
return new Date(d.setDate(diff));
}
The same as the original answer, but in one line:
var tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)
The numbers stand for 24 hours 60 minutes 60 seconds 1000 milliseconds.
you can try this:
function Tomorrow(date=false) {
var givendate = (date!=false) ? new Date(date) : new Date();
givendate.setDate(givendate.getDate() + 1);
var day = givendate.getUTCDate()
var month = givendate.getUTCMonth()+1
var year = givendate.getUTCFullYear()
result ="<b>" + day + "/" + month + "/" + year + "</b>";
return result;
}
var day = Tomorrow('2020-06-30');
console.log('tomorrows1: '+Tomorrow('2020-06-30'));
console.log('tomorrows2: '+Tomorrow());
//to get date of tomorrow
let tomorrow=new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()+1}-${(new Date()).getDate()+1}`);
//for dd-mm-yy format
tomorrow=`${tomorrow.getDate()}-${tomorrow.getMonth()+1}-${((tomorrow.getFullYear()).toString()).slice(-2)}`;
document.write(tomorrow)
//-----------Date Configuration march 18,2014----------------------
//alert(DateFilter);
var date = new Date();
y = date.getFullYear(), m = date.getMonth();
var EndDate = new Date();
switch (DateFilter) {
case 'today': var StartDate = EndDate; //todays date
break;
case 'yesterday':
var d = new Date();
var previousDate = new Date(d.getTime() - 1000 * 60 * 60 * 24);
var StartDate = new Date(previousDate.yyyymmdd()); //yesterday Date
break;
case 'tomorrow':
var d = new Date();
var NextDate = new Date(d.getTime() + 1000 * 60 * 60 * 24);
var StartDate = new Date(NextDate.yyyymmdd()); //tomorrow Date
break;
case 'thisweek': var StartDate = getMonday(new Date()); //1st date of this week
break;
case 'thismonth': var StartDate = new Date(y, m, 1); //1st date of this month
break;
case 'thisyear': var StartDate = new Date("01/01/" + date.getFullYear()); //1st date of this year
break;
case 'custom': //var StartDate = $("#txtFromDate").val();
break;
default:
var d = new Date();
var StartDate = new Date(d.getTime() - 30 * 24 * 60 * 60 * 1000); //one month ago date from now.
}
if (DateFilter != "custom") {
var SDate = $.datepicker.formatDate('#Config.DateFormat', StartDate); $("#txtFromDate").val(SDate);
var EDate = $.datepicker.formatDate('#Config.DateFormat', EndDate); $("#txtToDate").val(EDate);
}
//-----------Date Configuration march 18,2014----------------------
var curDate = new Date().toLocaleString().split(',')[0];
Simply! in dd.mm.yyyy format.
Date.prototype.NextDay = function (e) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + ("string" == typeof e ? parseInt(e, 10) : e));
}
// tomorrow
console.log(new Date().NextDay(1))
// day after tomorrow
console.log(new Date().NextDay(2))

js date object based on strings

I want to make a js date object based on strings in format YYYYMMDD and HHMMSS.
function makeTimeStamp(myDate, MyTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substring(0, 3);
var MM = myDate.substring(4, 5);
var DD = myDate.substring(6,7);
var HH = myTime.substring(0,1);
var MM = myTime.substring(2,3);
var SS = myTime.substring(4,5);
jsDate =
}
If you meant to be creating a Date object for given year, month, day, hours, minutes and seconds, you can use new Date(year, month - 1, day, hours, minutes, seconds) to create a Date instance for it. Note that the month is 0 based, January is 0, February 1, etc. Hence the MM - 1;
function stringToDate(myDate, myTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substr(0, 4);
var MM = myDate.substr(4, 2);
var DD = myDate.substr(6, 2);
var HH = myTime.substr(0, 2);
var mm = myTime.substr(2, 2);
var SS = myTime.substr(4, 2);
var jsDate = new Date(YYYY, MM - 1, DD, HH, mm, SS);
return jsDate;
}
// returns a Date object for given date and time
var jsDate = stringToDate("20110818", "191500");
// returns 1313687700000
var timestamp = jsDate.getTime();
Note that I'm using string.substr(start_position, length) as you can easily see the length of the returned value.
You can try Date.js which is a date library. http://www.datejs.com/
You can convert those date and time formats in to ISO format pretty easily (e.g. "2011-08-18T12:34:56") and use a regular expression to make sure the arguments are formatted properly:
function makeTimestamp(myDate, myTime) {
var ds = myDate.match(/^(\d{4})(\d\d)(\d\d)$/)
, ts = myTime.match(/^(\d\d)(\d\d)(\d\d)$/);
if (!ds || !ts) { return null; }
return new Date(ds.slice(1,4).join("-") + "T" + ts.slice(1,4).join(":"));
}
var d = makeTimestamp('20110818', '123456');
d // => Fri Aug 19 2011 12:34:56 GMT-0400 (EDT)
you can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, 'YYYYMMDD HHMMSS');
`
You can get date string by using this method:
const dateString = timeSolver.getString(date, format);
Hope this will help you!

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources