Timestamp calculated from the current time instead the source date - javascript

I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~

After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.

Related

How to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format? [duplicate]

This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I have to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format.
And I should compare two dates, which are in dd/mm/yyyy hh:ii AM/PM format.
JS:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
var dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var mm = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var strTime = dd + '/' + mm + '/' + date.getFullYear() + " " + hours + ':' + minutes + ' ' + ampm;
let me first note that by default javascript would be giving you the time in UTC.
A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time are the same as the UNIX epoch, which is the predominant base value for computer-recorded date and time values. (refer)
The above is true when you use the Date() function to create a Date Object
Using ES20xx, you can use a template literal (not supported in IE) and the padStart(not supported in IE) string extension to format the Date object to your liking as shown in the snippet below.
I have also date.toLocaleString() which gives the string in a format that is commonly used in the region from where the browser is running the function
The toLocaleString() method returns a string with a language sensitive
representation of this date. The new locales and options arguments let
applications specify the language whose formatting conventions should
be used and customize the behavior of the function. In older
implementations, which ignore the locales and options arguments, the
locale used and the form of the string returned are entirely
implementation dependent.(refer)
So the easy way to do this would be to add 15 minutes to the Unix timestamp obtained from the Date Object and formatting it with toLocaleString(this is the first snippet)
You can also compare the two date objects below as you would any integer
var dt1 = (new Date()).getTime();//Unix timestamp (in milliseconds)
console.log("Current date Unix timestamp(ms)")
console.log(dt1)
console.log("15 mins later date Unix timestamp(ms)")
console.log(dt1+900000)//15min=900000ms (15*60*1000)
var dt = new Date(dt1);
var dt2= new Date(dt1+900000)
console.log("Unformatted dates 15 min apart (ISO 8601 / UTC)")
console.log(dt)
console.log(dt2)
console.log("Formatted dates 15 min apart (According to your timezone)")
console.log(dt.toLocaleString())
console.log(dt2.toLocaleString())
Below is the longer snippet that involves formatting the date object while displaying it. I feel this is not as optimal as the method above. But still does the job.
var dt = new Date();
console.log(dt);
const localdte = dt.toLocaleString();
console.log(localdte);
const [dated, time, ampm] = localdte.split(' ');
const [hh, mm, ss] = time.split(':');
var date = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
dt.getHours().toString().padStart(2, '0')}:${
dt.getMinutes().toString().padStart(2, '0')}`
console.log("Date right now");
console.log(date);
console.log("date 15 mins later");
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?(dt.hours==23?00:dt.getHours()+1):dt.getHours()).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("24 hour format " + date15);
if (ampm == "PM" && hh != 12 && hh!=00) {
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?(dt.getHours()+1)%12:dt.getHours()%12).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("12 hour format " + date15 + ampm); //12 hour format
} else if (hh == 00) {
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?1:12).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("12 hour format " + date15 + ampm);
} else {
console.log("12 hour format " + date15 + ampm); //12 hour format
}
const dateISO = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), ((dt.getMinutes() + 15) % 60), dt.getMilliseconds());
console.log("ISO 8601 format (UTC)");
console.log(dateISO);
Note: there is a difference in the chrome console and the snippet console outputs. In the chrome console the output the date object is always formatted for local time. In the snippet console, the output of the date object is in UTC and ISO8601 compliant.
Thanks to #RobG for pointing out the errors in my previous answer.

convert ionic datetime to hour and min

I am using ionic date time component as below
<ion-item >
<ion-label>Time:</ion-label>
<ion-datetime displayFormat="h:mm A" pickerFormat="h mm A" [(ngModel)]="localEstDelTime"></ion-datetime>
</ion-item>
on ionViewDidLoad i am setting the value of localEstDelTime as:
var d = new Date()
var dt = d.setTime(d.getTime() + (5.5 + 2)*60*60*1000)
this.localEstDelTime = dt.toISOString()
basically 5.5 hours has been added to make it for indian time zone which is GMT + 5.5 and for this use case the time is supposed to be shown plus 2 hours of current time.
now, the requirement is let's say end user added another extra hour through UI then i want to get that hour and time in the local time zone. My code does not work properly as below:
var storeEstDelTime = Date.parse(this.localEstDelTime)
var date = new Date(storeEstDelTime)
var hours = date.getHours() + 5.5
var minutes = date.getMinutes()
var ampm = Number(hours) >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0′ should be ’12′
var minutesStr = Number(minutes) < 10 ? '0'+ minutes : minutes;
estDeliveryTime = hours + ':' + minutesStr + ' ' + ampm;
so i need estDeliveryTime to be just hh:mm AM/PM format. my above code need to be fixed.
It is always a good idea to convert your date to UTC time set always as it is a common standard. Like for input date, just convert the date like this:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
Now, when you take input from user for delivery time(for that extra hour), do the same thing to that date, and add that hour to the utcDate and in the end, convert the UTC date to GMT date with 5.5 as for IST.
Hope this helps:)
npm i --save date-fns
import {format} from "date-fns" in your .ts file
let example_time = "2019-11-30T14:42:30.951+08:00";
format(new Date(example_time), "HH:mm");
console.log(example_time) => '14:42'

Convert my my variable into a 12/12 time format using moment.js

I need to convert my time that is in military time 24 hours time to regular 12/12 time.
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
console.log("nextArrival2", typeof nextArrivalFinal2)
console.log("nextArrival2", nextArrivalFinal2)
var convertedDate = moment(new Date(nextArrivalFinal2));
console.log('converted1', convertedDate)
console.log('converted', moment(convertedDate).format("hh:mm:ss"));
nextArrivalFinal2 displays the time as a string in HH:MM:ss format. But when I plug it into the moment js, it says it is an invalid date.
You are not parsing the time with moment.js, the line:
var convertedDate = moment(new Date(nextArrivalFinal2));
is using the date constructor to parse a string like "13:33:12", which will likely return an invalid date in every implementation (and if it doesn't, it will return something that may be very different to what you expect).
Use moment.js to parse the string and tell it the format, e.g.
var convertedDate = moment(nextArrivalFinal2, 'H:mm:ss'));
Now you can get just the time as:
convertedDate().format('h:mm:ss a');
However, if all you want is 24 hr time reformatted as 12 hour time, you just need a simple function:
// 13:33:12
/* Convert a time string in 24 hour format to
** 12 hour format
** #param {string} time - e.g. 13:33:12
** #returns {sgtring} same time in 12 hour format, e.g. 1:33:12pm
*/
function to12hour(time) {
var b = time.split(':');
return ((b[0]%12) || 12) + ':' + b[1] + ':' + b[2] + (b[0] > 12? 'pm' : 'am');
}
['13:33:12','02:15:21'].forEach(function(time) {
console.log(time + ' => ' + to12hour(time));
});

json object contains php DateTime, how to convert to pretty date string

So i have a json object, which returned me basically a datetime object, now the question, what is the most efficient way of formatting this to a single string human readable format, in the users (client) local timezone... In javascript
created: {
timezone: {
name: "America/New_York",
location: {
country_code: "US",
latitude: 40.71417,
longitude: -74.00639,
comments: "Eastern Time"
}
},
offset: -18000,
timestamp: 1454125056
},
If the timestamp is an ECMAScript time value (i.e. milliseconds since 1970-01-01T00:00:00Z) then you can give that value directly to a Date object:
var d = new Date(1454125056); // 1970-01-17T19:55:25.056Z
however it is more likely seconds, so multiply by 1,000:
new Date(1454125056*1000).toISOString(); // 2016-01-30T03:37:36.000Z
which will create a Date for that moment in time. The offset should probably be ignored, unless it was used in the creation of the time value, in which case it should be added if it follows the ISO convention of negative for west and positive for east. If it follows the ECMAScript convention, the opposite applies.
I'll assume ISO, and since it appears to be seconds, you can apply it to the UTC seconds:
var offset = -18000;
d.setUTCSeconds(d.getUTCSeconds() + offset);
console.log(d.toISOString()); // 2016-01-29T22:37:36.000Z
Using plain Date methods thereafter will return values based on the host system's timezone settings.
var timeValue = 1454125056;
var offset = -18000;
var d = new Date(timeValue*1000);
document.write(d.toISOString() + '<br>' + d);
d.setUTCSeconds(d.getUTCSeconds() + offset);
document.write('<br>' + d.toISOString() + '<br>' + d);
There are many questions here on how to format a date string from a Date object.
Note that javascript is only required consider the daylight saving rules in force at the current time as if they had always existed, so be careful with historical dates.
Suppose this json object loaded in $created variable. i assume you mean php.
in PHP :
$obj = json_decode($created, true);
$timezone_name = $obj['timezone']['name'];
$timezone_location_country_code = $obj['timezone']['location']['country_code'];
$timezone_location_latitude = $obj['timezone']['location']['latitude'];
$timezone_location_longitude = $obj['timezone']['location']['longitude'];
$timezone_location_comments = $obj['timezone']['location']['comments'];
$offset = $obj['offset'];
$timestamp = date('m/d/Y', abs($obj['timestamp']));
in Javascript :
getDate: function(timestamp){
// Multiply by 1000 because JS works in milliseconds instead of the UNIX seconds
var date = new Date(timestamp * 1000);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we’ll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
month = (month < 10) ? ‘0’ + month : month;
day = (day < 10) ? ‘0’ + day : day;
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds: seconds;
return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hours + ‘:’ + minutes;
}

Converting Date time formats

What's the best way to convert date time formats using javascript?
I have this.. "2015-08-06T00:39:08Z"
and would like to change it to
"06/08/2015 12:39pm"
You could do it manually by instantiating a Date object:
var d = new Date('2015-08-06T00:39:08Z');
Then using the Date methods (like getDay or getUTCFullYear) to get the information needed and build the formatted string.
Or, if you don't mind relying on a library, you could use http://momentjs.com/ that provides a lot of methods, and particularly the format method: http://momentjs.com/docs/#/displaying/format/
// Example with moment.js
var formattedDate = moment('2015-08-06T00:39:08Z').format("MM/DD/YYYY hh:mma");
alert(formattedDate);
Use newDate() method, then Date Get Methods. Examples are explained on w3Schools
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
With pure javascript:
code:
function formatDate(input) {
var datePart = input.match(/\d+/g),
year = datePart[0], // get only two digits
month = datePart[1],
day = datePart[2];
var h = parseInt(input.substr(input.indexOf("T") + 1, 2));
var m = parseInt(input.substr(input.indexOf(":") + 1, 2));
var dd = "AM";
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
m = m < 10 ? "0" + m : m;
alert(day + '/' + month + '/' + year + ' ' + h.toString() + ':' + m.toString() + dd);
}
formatDate('2015-08-06T00:39:08Z'); // "18/01/10"

Categories

Resources