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

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;

Related

Unix to datetime object using Javascript

I am trying to convert a unix time stamp to a datetime object using javascript but am getting a strange output.
The unix timestamps I'm using are 1420243200000 and 1420272000000. My javascript code looks like this:
function timeConverter(UNIX_timestamp){
// var a = new Date(UNIX_timestamp*1000);
// var year = a.getFullYear();
// var month = a.getMonth()+1;
// var date = a.getDate();
// var hour = a.getHours();
// var min = "0" + a.getMinutes();
// var sec = "0" + a.getSeconds();
// var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min.substr(-2) + ':' + sec.substr(-2) ;
// return time;
var myDate = new Date( UNIX_timestamp *1000);
time = myDate.toLocaleString();
return time;
}
Neither the commented or uncommented attempts produce the correct date. I keep getting 9/18/46975, 6:00:00 PM and 8/17/46976, 2:00:00 AMas the answers and I can't figure out what's going wrong.
Your timestamp appears to already be in milliseconds. Don't multiply with 1000.
Calling it "UNIX_timestamp" is misleading. Unix timestamp is seconds elapsed since epoch. Timestamps from JS functions (like Date.now() and +new Date()) are milliseconds elapsed since epoch.
try myDate = new Date(1420243200000);
From the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Call the constructor new Date(value);. Where value is "Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)."

JavaScript - Convert date stirng yyyyMMddHHmmss to date object yyyy-MM-dd HH:mm:ss

I have this date : 2014071109080706ICT
I need to convert it to Date object in JS
I tried to create new object new Date("2014071109080706ICT") but I get error Invalid date
I also tried cut date string to "20140711090807" and create new Date object but it always generate error : Invalid date
How can i do it ?
You can try to use moment.js .
http://momentjs.com
There are some examples in docs page. One of them is:
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z");
http://momentjs.com/docs/#/parsing/
You can try:
moment("20140711090807+0600", "YYYYMMDDHHmmssZZ");
I think "06ICT" is the timezone info.
You just need to slice the string for each segment and create the date object based on those parts.
var str = "20140711090807";
var year = str.substring(0, 4);
var month = str.substring(4, 6);
var day = str.substring(6, 8);
var hour = str.substring(8, 10);
var minute = str.substring(10, 12);
var second = str.substring(12, 14);
var date = new Date(year, month-1, day, hour, minute, second);
PS: month index is between 0 and 11 so you need to subtract it by 1.

Extract Month or Day or Year from Timestamp

I would like to know how to get a specific date format (date or month or day or year) from a timestamp. I am wanting to use this in a view with Backbone JS
var d = new Date(1397639141184);
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
1.If it's JavaScript Timestamp(i.e., in milliseconds)
var date = new Date(13976391000);
var date = date.getDate(); //returns date (1 to 31) you can getUTCDate() for UTC date
var day = date.getMonth(); // returns 1 less than month count since it starts from 0
var year = date.getFullYear(); //returns year
// You can also use getHours(), getMinutes() and so on
2.If it's database timestamp - example 2013-03-14T02:15:00
var date = new Date('2013-03-14T02:15:00'); // Works in all browsers
var date = new Date('2013-10-18 08:53:14');// works in Chrome & doesn't work in IE/Mozilla
//note that its a string and you use the same above functions to get Date,month & year

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

javascript: get month/year/day from unix timestamp

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.

Categories

Resources