adding Date and Time in javascript to get in ISOFormat - javascript

I got the date in ISOFormats and time in 12hrs format. i need to combine togeather and get the output in ISOFormat using javascript. Im doing this in reactJs so using external libraries is fine
date = "2019-02-19T00:00:00.000Z"
startTime = "04.42PM"
outputDateTime = "2019-02-19T11:12:37.680Z"

Have a look at momentjs parse function.
Use it to convert the dates to moment objects and directly add them using the add function.
Example here

If you go pure vanilla I think this is fairly simple (AFAIK you only need hours and minutes and the zone is always fixed, if not, upgrade).
var yourDate = "2019-02-19T00:00:00.000Z";
var yourTime = "04.42PM"
var dat = yourDate.split("T")[0];
var minutes = yourTime.split(".")[1].slice(0,2);
var isPm = yourTime.split(".")[1].slice(2) === "PM";
var hours = isPm ? parseInt(yourTime.split(".")[0]) + 12 : yourTime.split(".")[0];
var date = new Date(dat+ "T" +hours+":"+minutes+":00Z");
Basically, I decomposed the input strings into interesting parts, compensated for PM if needed and put them back together :)

Related

The problem of getting and working with dates in Js [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 months ago.
When working with the task, it became necessary to get dates from html, and to find out the time difference between them:
var now_time_div = document.getElementById("time_now_of");
var start_time_div = document.getElementById("time_when_start_of");
var time_now = now_time_div.textContent || now_time_div.innerHTML;
var time_start = start_time_div.textContent || start_time_div.innerHTML;
After that, without thinking about the format of the data, I wanted to find the time difference in ms:
var worked_time = time_now - time_start
That didn't work, because we are working with a string.
After entering the directory, I found the Date.parse() function, which returns the amount of time that has passed since the given date:
var worked_time = Date.parse(time_start);
but it turned out that it works only with a correctly submitted strig, for example
We need to have:
Date.parse('01 Jan 1970 00:00:00 GMT');
We have:
Date.parse('21.09.2022, 15:34:21')
Maybe someone knows an easy way to implement this without rebuilding the string?
If you don't want to bring in a library like moment.js, you can just massage the date string a bit so it can be parsed correctly
const dateString = '21.09.2022, 15:34:21';
const curDate = dateString.split(',')[0].substring(0, 10).split('.');
const curTime = dateString.split(',')[1];
const parsed = `${curDate[1]}'/'${curDate[0]}'/'${curDate[2]} ${curTime}`;
console.log(new Date(parsed).toString()); // Properly formatted date
You can used this parsed variable to compare to other properly formatted dates
You can use moment.js to parse custom date formats just as in for example Java:
https://momentjs.com/docs/#/parsing/string-format/
After that you can simply convert it to a js date using the toDate function: https://momentjs.com/docs/#/displaying/as-javascript-date/
Edit Example:
var mDate = moment('2022-09-21 10:15:00', 'YYYY-MM-DD HH:mm:ss');
var jsDate = mDate.toDate();

How can i customize the js new Date() instance

When i use the new Date() instance i get something like
2020-12-10T12:30:18.108Z
the problem is that by me the hour on my local machine is 13:30 - but it gives me one hour earlier so 12:30 in the current time. How can i customize to give me the right time of my local machine ?
Also i don't know the meaning of the last four character after the . sign
108Z
all i need is to insert in my db the hour and the date without this signs
2020-12-10T12:30:18
is there any other solution except manupulating the string directly ?
You're using UTC Date I guess. You can try to use .toLocaleString() on your date time object.
Maybe use like that
var datetime = new Date();
var now = datetime.toLocaleString();
This should get you something like this: 10/12/2020, 8:47:15 AM
UPDATED
Another option if you want to maintain format and just remove T and Z characters is to replace string
You can try this:
var datetime = new Date();
var now = datetime.toISOString().replace('Z', '').replace('T', '');

Timesheet hours difference in moment.js

I have a string '08:30-16:30' describing working hours.
I also have the time someone has worked, in HH:mm format,eg.09:15
What is the easiest-fastest way to convert them in dates and find the difference in HH:mm format ?
Should i use Moment.js?
Also,i need the difference in minutes or seconds so that i can do comparisons with that.
I would be grateful if you could give me some examples.
For finding the difference between the working hours, you could make use of MomentJS.
Example:
var working_hours = '08:30-16:30';
var hours_arr = working_hours.split('-'); // Gives an array with ['08:30', '16:30']
var start = moment(hours_arr[0], "HH:mm");
var end = moment(hours_arr[1], "HH:mm");
var duration = moment.duration(end.diff(start));
var minutes = parseInt(duration.asMinutes());
The minutes variable would contain the difference in minutes.

Transforming date string from one timezone to another in JavaScript

I have spent several hours trying to figure out how JavaScript works with dates. I have come across this question, but it does not seem to asnwer my specific question.
My input is a string like this:
"2018-02-19T07:00:00Z"
My goal is to transform this into a datetime which would differ from the original date by 4 hours - WITHOUT ANY TIMEZONE (!):
"2018-02-19T11:00:00Z"
Is it possible in JavaScript ?
Check out all the functions relating to "UTC" and "ISO" on the Date docs.
var input = "2018-02-19T07:00:00Z";
var t = new Date(input);
t.setUTCHours(t.getUTCHours()+4)
var iso = t.toISOString().replace(/\.\d+/,'');
console.log(iso);
(I added a little regex to get rid of the milliseconds so it matches your expected output, you can remove that if the miliseconds don't matter, it's valid ISO either way.)
It's 4 lines of code, you do not need a library.
In addition to #Occam'sRazor answer, you could also do it without using the Date object, by using some String manipulations :
var str = "2018-02-19T07:00:00Z";
var timeZoneHours = +str.split('-').pop().split(':')[0].split('T').pop() + 4;
console.log(timeZoneHours);
str = str.substring(0,str.indexOf(':') -2) + (timeZoneHours < 10 ? '0' + timeZoneHours.toString() : timeZoneHours.toString()) + str.substring(str.indexOf(':'), str.length);
console.log(str);

Need help to resolve the issue when converting epoch date to human readable format - Javascript

My java script application uses .net web service to get the data from back end. Everything works fine except for date / time conversion. I need to convert the epoch date returned by service to user's local browser date.
The web service returns date in the below format,
/Date(1335341422660-0500)/
This is what I have done to convert this to human readable date,
I strip out everything after hyphen (-) and use the remaining data for date conversion
var dateVal=dateField.replace(/-.*\)/g,')');
var date = new Date(parseFloat(dateVal.substr(6)));
var dateArray=date.toString().split(" ");
if(dateArray.length>3){
timeZone=("("+dateArray[4])+")"
}
var month=date.getMonth() + 1;
var year=date.getFullYear();
var date=date.getDate();
var hours= date.getHours();
var offset=date.getTimezoneOffset();
var finalDateStr=(year+"-"+month+"-"+dateValue)+" "+hours+":"+
minutes+":"+seconds+" "+timeZone;
For the above epoch value, expected date is,
4/24/2012 9:10:22 PM - This date is displayed in a .net application which is actually the source application that inserts this date in to MS SQL server whenever a new item is created / updated. They convert the SQL server date to local date (using .net) and display it in UI.
but when I form the date using the above script I am getting the value as,
2012-4-25 4:10:22 (EDT) (7 hours more compared to above date).
I am not sure where I am wrong.. Can some one help me figure out this issue?
For such date manipulations, you might want to consider using Moment.js.
Not sure if this is a great way to fix this issue...
This is what I did and seems to work fine... Again I dont think this is a fool proof solution but I checked in various time zones (with / without daylight saving time) and it seems to work......
var dateVal=dateField.replace(/-.*\)/g,')');
var date = new Date(parseFloat(dateVal.substr(6)));
var dateArray=date.toString().split(" ");
var timeZone="(Local Time)";
if(dateArray.length>3){
timeZone=("("+dateArray[4])+")"
}
var date2=dateField.split("-");
var dateOffset=(date2[1].toString().replace(")","").replace("/",""));
if( date.toString().toUpperCase().indexOf("DT")!==-1){
date.setHours(date.getHours()-(parseFloat(parseFloat(dateOffset).toString().replace(/0*$/, ''))+2));
}else{
date.setHours(date.getHours()-(parseFloat(parseFloat(dateOffset).toString().replace(/0*$/, ''))+1));
}
var month=date.getMonth() + 1;
var year=date.getFullYear();
var dateValue=date.getDate();
var hours= date.getHours();
var minutes= date.getMinutes();
var seconds=date.getSeconds()
var finalDateStr=(year+"-"+month+"-"+dateValue)+" "+hours+":"+
minutes+":"+seconds+" "+timeZone;

Categories

Resources