Conver Timepicker time to utc using Timepicker (ng-bootstrap) - javascript

I am using https://valor-software.com/ngx-bootstrap/#/timepicker in my angular project.
I have one task o covert that time to UTC before I request to server.
When I select Time from timepicker value coming is as below.
Now, I have created one function to convert it to UTC using moment.js
static FormatimeSpanBeforeSubmit(date: Date | string ) {
const dateFromTimePicker = date as Date;
// Convert it to format "HH:mm:ss"
let formatedTime = moment.utc(dateFromTimePicker).format('HH:mm:ss');
// Split details in array because I want seconds as always "00"
let list = formatedTime.split(/[\s:]+/);
// Updating last value ""ss" to "00"
formatedTime = formatedTime.replace(new RegExp(list[list.length -1] + '$'), '00');
//Final value
return date ? formatedTime : null;
}
Expected Output : It should convert my time as "9:51:00"
Current Output : "10:54:00"
Please help me and guide me how can I get correct value.
Comment :
(2) As per comments from Hoài Nam I have updated my code like below and in that I am still getting 10:54:00
Please find below two images

i can't comment so i will reply you at here:
i found another solution at here https://stackoverflow.com/a/40381090/9768008
this is what i tried:
var time = 1569326290681; //Tue Sep 24 2019 18:58:10 GMT+0700 (Indochina Time)
var os = new Date().getTimezoneOffset();
var converted = new Date((time + (os * 60 * 1000)));
console.log(converted); // Tue Sep 24 2019 11:58:10 GMT+0700 (Indochina Time)

Issue was date format coming from server was wrong. So, I was getting GMT+ 6.55 instead of GMT+ 8.
Thanks for helping.
Addressed both solution. Mine as well as of #HoàiNam are correct.

Related

Merge and convert date and time in IST format to UTC format

I am trying to convert date and time entered by customer from IST format to UTC format because I am storing all data in database in UTC format. But the problem I am facing is I am getting different timestamp in which the date is completely different and also the date time doesn't seems to UTC datetime. What I am trying to do is, I am merging first the date and time in IST format and then I am converting it to UTC format. and then separating date and time from them. My nodejs server is hosted in aws EC2 instance.
deliveryOrPickUpDate = req.body.deliveryOrPickUpDate;
deliveryOrPickUpTime = req.body.deliveryOrPickUpTime;
console.log(deliveryOrPickUpDate);
console.log(deliveryOrPickUpTime);
let deliveryOrPickUpTimehh = deliveryOrPickUpTime.substring(0,2);
let deliveryOrPickUpTimemm = deliveryOrPickUpTime.substring(3,5);
console.log("deliveryOrPickUpTimehh is :", deliveryOrPickUpTimehh);
console.log("deliveryOrPickUpTimemm is : ", deliveryOrPickUpTimemm);
ISTDateTime = deliveryOrPickUpDate + 'T' + deliveryOrPickUpTimehh + ':' + deliveryOrPickUpTimemm + ':' + '00.000'; //Constucting in T format but without Z to say its not UTC and just any other time
console.log("ISTDateTime selected is : ", ISTDateTime);
utcDate = new Date(ISTDateTime); //Converting IST to UTC here
console.log(utcDate);
utcDate.setDate(utcDate.getHours() - 5);
utcDate.setDate(utcDate.getMinutes() - 30);
dateISTString = utcDate.toUTCString(); // date in IST format
console.log("India time now is ", dateISTString);
dateUtc = utcDate.toISOString().slice(0,10);
console.log("Date in UTC is : ", dateUtc);
timeUtc = utcDate.toISOString().slice(11,19);
console.log("Time in UTC is : ", timeUtc);
Example Console output is below
2023-03-30
22:34:00
deliveryOrPickUpTimehh is : 22
deliveryOrPickUpTimemm is : 34
ISTDateTime selected is : 2023-03-30T22:34:00.000
2023-03-30T17:04:00.000Z
India time now is Sat, 04 Mar 2023 17:04:00 GMT
Date in UTC is : 2023-03-04
Time in UTC is : 17:04:00
These are the two input date and time:
2023-03-30
22:34:00
The easiest way would be to use Luxon.
Luxon is small, clean and modern. It also doesn't drag along the entire tzdb — it uses native internationalization support in Node and browser.
const { DateTime } = require('luxon');
const date = "2023-03-30";
const time = "22:34:00";
const IST = 'Asia/Kolkata' ;
const dtLocal = DateTime.fromISO(`${date}T${time}`, { zone: IST } );
const dtUtc = dtLocal.toUTC();
console.log(`LOCAL: ${dtLocal.toFormat('yyyy-MM-dd HH:mm:ss')} IST`);
console.log(`UTC: ${dtUtc.toFormat('yyyy-MM-dd HH:mm:ss')} UTC`);
Which yields:
LOCAL: 2023-03-30 22:34:00 IST
UTC: 2023-03-30 17:04:00 UTC
Edited to note: to get the date and time individually, as strings, one can read the documentation and note that an instance of a Luxon DateTime comes with these methods:
.toISODate() method
.toISOTime()
Which will do exactly what you want.
One should note that these two methods are largely convenience wrappers around .toFormat().
.toISODate() is pretty much just .toFormat('yyyy-MM-dd'), and
.toISOTime() is pretty much just .toFormat('HH:mm:ss')`
with some logic to interpret the options and tweak the format string appropriately.

Date and time based json element using javascript

I have a json response like this :
{
"NO_INSPECTION": "55",
"NO_SURAT": "00055",
"DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}
How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)
I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?
Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:
var response = {
DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}
var raw = response.DATE_OF_DESCRIPTION;
var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];
var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);
var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);
// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);
console.log(date);
console.log(dateTime);
This gives the output
Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)
JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":
response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];
BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)
You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!
I've googled "javascript date parsing library" and this is what I've found:
http://momentjs.com/ <--- I think that's what you're looking for!

Unix offset with fullCalendar difference

I want to place a check when I'm getting a momentjs instance through fullCalendar.
I'm at the eventRender callback
var calendar = $('#calendar').fullCalendar('getCalendar');
var atime = calendar.moment();
var atime_h = atime.format("HH:mm");
atime = atime.unix();
var start = calendar.moment(event.start);
var start_u = start.unix();
var start_h = start.format("HH:mm");
console.log(atime);
console.log(atime_h);
console.log(start_u);
console.log(start_h);
Now what that logs is this:
1408024477
15:54
1407888000
00:00
1408024477 == Thu Aug 14 15:54:37 2014 == is correct
But 1407888000 == Wed Aug 13 02:00:00 2014, where I would expect 00:00 instead of 02:00
So there's a difference between the event .unix()/format.() and the moment I created.
Anyone got a clue what's going on?
Edit:
So what happens is that if I create two new moments: moment() and a moment().utc(), I get the same timestamp for both. But when I then display them, there is a difference of two hours.
The .utc one returns two hours in the past, the one without the correct one for me. The timestamp is not two hours back.
But with the event.start (which has _isUTC=true, the timestamp is two hours in the future (!), and it displays it correct when formatted.
So maybe I need to have my event.start to be not UTC and two hours back somehow?
Edit by request in comment, this is what I use now:
var start = calendar.moment(event.start);
console.log(start);
start_utc = new Date(start.year(), start.month(), start.date(), start.hour(), start.minute(), start.second());
var start = calendar.moment(start_utc);
console.log(start);
Try converting your event.start date to utc first, here's how to do it in vanilla js:
start_utc = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
Then you can call .unix() on it and it should give you the expected timestamp.

Simple Javascript date conversion

I have this - Tue, 03 Apr 2012 05:00:33 GMT
Need this - 20120323111106
Google has failed me, I think I just don't know exactly what im searching for so I kept it simple here with the question.
EDIT: The dates do not match obviously, just looking to get it in that format.
Good answer (later edited):
I think this is what you are looking for :
function addZero(val){
if (parseInt(val) < 10) return "0" + val;
return val;
}
var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT");
console.log(dt.getFullYear() + addZero(dt.getMonth()) + addZero(dt.getDay()) + addZero(dt.getHours()) + addZero(dt.getMinutes()) + addZero(dt.getSeconds()))
Initial wrong answer :
var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT")
var miliseconds = dt.getTime();
I've tested it and my computer converted it automatically to GMT +3 (my timezone), you can play with that according to your timezone.
Writing a function to parse a string should work for you. By the looks of it, any date string that you currently have will be the same length. If this is the case this should be relatively easy. Just make sure your strings are in this format before you pass them in as arguments.
function parse(string) {
var out = "yyyymmddhhmmss"
out.charAt(0) = string.charAt(13);
out.charAt(1) = string.charAt(14);
out.charAt(2) = string.charAt(15);
out.charAt(3) = string.charAt(16);
//if else statements for each month converting to numbers
if (string.substring(9,12).equals("Apr")) {
out.charAt(4) = '0';
out.charAt(5) = '4';
}
out.charAt(6) = string.charAt(18);
out.charAt(7) = string.charAt(19);
...etc for the remaining values
return out
}
My numbers for character indices may be off, but if you use this idea, it should set you straight. Define a function and pass in the dates in the format you have, and out will come the dates in the format you want.

Javascript convert seconds to a date object

How can I convert seconds into a datetime object in javascript.
Examples:
1.3308313703571
1.6324722385401
This is from a series of points and when they occurred. I understand 1.23323 more then seconds, but I can not change the value, being pulled from an api.
You can try like this:
function toDateTime(secs) {
var t = new Date(1970, 0, 1); // Epoch
t.setSeconds(secs);
return t;
}
Info on epoch date.
You can pass unix timestamp milliseconds as an argument to the Date constructor:
const secs = 30;
const output = new Date(secs * 1000);
console.log(output);
#UVM's answer is helpful, but slightly incomplete if you're dealing with timezones (i.e. UTC vs local time). With timezones, start with UTC using Date.UTC and Date.setUTCSeconds to get a true UTC date and time.
function toDateTime(secs) {
var t = new Date(Date.UTC(1970, 0, 1)); // Epoch
t.setUTCSeconds(secs);
return t;
}
You can then use a library like Moment to convert/format it to a local timezone.
your example values have a decimal.. looking like you are trying to convert 1.something seconds into a date..
Meanwhile check this example here on the correct seconds to date conversion.. you could view their js sources.
The question seems to have already been answered but this may be helpful for those attempting to do something similar to ruby's Time.at() method.
function formatDateTime(input){
var epoch = new Date(0);
epoch.setSeconds(parseInt(input));
var date = epoch.toISOString();
date = date.replace('T', ' ');
return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString().split(' ')[0];
};
I dunno how it be 10 years ago, but now it can solve just doing next:
let sec = 1628618888939
let time = new Date(sec)
let normalDate = new Date(sec).toLocaleString('en-GB',{timeZone:'UTC'})
time: "Tue Aug 10 2021 21:08:08 GMT+0300 (Eastern European Summer Time)"
normalDate: "10/08/2021, 18:08:08"
If in the future u will have problems like this, I can advise read about functions that relate to your question, and solution will come.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Categories

Resources