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

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();

Related

How to parse the date string in YYYY-MM-DD format [duplicate]

This question already has answers here:
Format JavaScript date as yyyy-mm-dd
(50 answers)
Closed 2 years ago.
I have date string in the format '2020/02/25 23:58:08' . I want to parse it to '2020-02-25".
Note : Initially date is in string format, after conversion whether it is in date or string format it doesn't matter.
file.js
function test (filepath) {
let date = "2020/02/25 23:58:08";
date = date.replace("//"/gi,"-");
// I am not familiar with regular expressions, I want to omit the data related to hours, seconds extra
}
When I ran the program, I gotUncaught ReferenceError: gi is not defined, gi is to globally replace
Try this
let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))
let date = `2020/02/25 23:58:08`;
let parsedDate = date.split(" ")[0].replace(/\//gi,'-');
console.log(parsedDate);
There is an error in the line using regex, should be:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
Then to get only the date, you can get the first 10 characters:
date.slice(0,10)
Final code:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
date.slice(0,10)
Although there are other ways to do it, you can use a library like momentJs which includes methods for this, like moment.format, it gives so many possibilities. But if you have a small case this is fine.

adding Date and Time in javascript to get in ISOFormat

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 :)

Javascript: How to convert exif date time data to timestamp? [duplicate]

This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);

Javascript time formatting [duplicate]

This question already has answers here:
Converting 24 hour time to 12 hour time w/ AM & PM using Javascript
(24 answers)
Closed 5 years ago.
I have this time in a variable called lastdate in javascript.
07:31:00
How can I show AM or PM using format specifier in Javascript..Like I use in php "%p" .
Is there any method to use in javascript. Any help is much appreciated.
Assuming that your time string will be in 24H format:
1.) Split time string into array.
2.) Create new Date object.
3.) Map the array to create integers. (this can also be done on each variable in the below method)
4.) Set the hours, minutes, and seconds to values of the generated array.
5.) Convert Date object to the local time string and use a Regex to create your new time string. (NOTE: toLocaleTimeString() may behave differently based on location)
/* Variable Defaults */
var timeString = '07:31:00';
var parts = timeString.match(/(\d{2}):(\d{2}):(\d{2})/);
var dateObject = new Date();
/* Cast `parts` as Integer */
Object.keys(parts).map(function(key, index) {
parts[key] = parseInt(parts[key]);
});
/* Set Hours/Minutes/Seconds */
dateObject.setHours(parts[1]);
dateObject.setMinutes(parts[2]);
dateObject.setSeconds(parts[3]);
/* Output New String */
var newTimeString = dateObject.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1$3')
/* Console Result */
console.log(newTimeString);
If you can bring in an external library, I'd recommend moment.js.
https://momentjs.com/
Then you can specify what you want with:
var lastdate = "07:31:00"
moment(lastdate, 'HH:mm:ss').format('LTS'); // 07:31:00 AM
Or if you want to be more explicit:
var lastdate = "07:31:00"
moment(lastdate, 'HH:mm:ss').format('HH:mm:ss A'); // 07:31:00 AM
Where the A means AM/PM. See https://momentjs.com/docs/#/displaying/format/.

Compare to dates Javascript? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Compare 2 dates with JavaScript
Hi,
I'm working on form validation for my application and i want to know where i would be to start looking at to find date comparison eg a start date and an end date. The dates inputted in to my application are in the form: DD/MM/YYYY.
Thanks in Advance,
Dean
If you are using the Javascript Date object, you can simply do:
var startDate = new Date();
var endDate = getEndDate();
if (endDate < startDate)
alert("Houston, we've got a problem!");
EDIT: Changed naming a bit just to stick to camelCase convention, even though I despise it.
this function lets you convert dates to timestamps with wich you could work:
http://caioariede.com/arquivos/strtotime.js
First, you'll want to parse the text into Date objects, then use the language's built-in date comparison. For example:
var dateStr = document.getElementById('foo').value;
var date = Date.parse(dateStr);
var dateStr2 = document.getElementById('foo2').value;
var date2 = Date.parse(dateStr2);
if (date < date2) {
// ...
}

Categories

Resources