Issue parsing dates on devices running iOS and MacOS (apple) operating systems - javascript

I have a web application that deals with different time zones. This app stores all the dates in UTC + 00:00 and converts the time to local time right before displaying it using a set of functions I wrote.
It all works well from converting the date string to a datetime object, converting the datetime object from UTC +00:00 to local time, but after I obtain the local datetime string
using date.toLocaleString(), I cannot format it as I want because it returns the following format: 3/23/2021, 9:19:00 PM, and literally all apple devices I tried cannot parse this string and convert it to a valid date.
I simply want to get the local time and format it from 3/23/2021, 9:19:00 PM to 23 Mar 2021 21:19. I have written a function that does this formatting for me but the browser cannot parse 3/23/2021, 9:19:00 PM from a string and convert it to a date object.
I am developing the application in React JS (JavaScript).
Here is the function that does the string parsing and date formatting:
const formatDateString = date => {
const parsed = new Date(Date.parse(date.replace(",", "")))
const months_string = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
const months_array = months_string.split(" ")
let output = ""
output = output + parsed.getDate() < 10 ? "0" + parsed.getDate() : parsed.getDate()
output = output + " " + months_array[parsed.getMonth()]
output = output + " " + parsed.getFullYear()
let hours = parsed.getHours() < 10 ? "0" + parsed.getHours() : parsed.getHours()
output = output + " " + hours
let minutes = parsed.getMinutes() < 10 ? "0" + parsed.getMinutes() : parsed.getMinutes()
output = output + ":" + minutes
return output
}

Your question states that your code "works well from converting the date string to a datetime object ..."
Would this work for you?
let d = new Date();
var options = { year: 'numeric', month: 'short', day: 'numeric' };
var s = d.toLocaleString('en-GB', options);
options = { hour: 'numeric', minute: 'numeric' };
s += ' ' + d.toLocaleString('en-GB', options);
console.log(s);
// output:
// 24 Mar 2021 10:26
Note: using 'en-GB' puts the date in "Day Month Year" order.

I ended up avoiding the parsing problem altogether and creating my own parser that will work for MY scenario. This solution only applies if your input format is same as mine, although it can be modified to work with virtually any date format. Here is the code:
export const formatDateStringApple = date_string => {
const months_string = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
const months_array = months_string.split(" ")
const split_datetime = date_string.split(" ")
const date = split_datetime[0].replace(",", "")
const _split_time = split_datetime[1].split(" ")
const time = _split_time[0]
const isPm = _split_time[1] == "PM" ? true : false
const split_date = date.split("/")
const split_time = time.split(":")
return `${split_date[1]} ${months_array[split_date[0] - 1]} ${split_date[2]} ${isPm ? split_time[0] + 12 : split_time[0] < 10 ? "0" + split_time[0] : split_time[0]}:${split_time[1]}`
}
Maybe (probably) there is a better way of doing this, but this is the quickest one I could come up with.

Related

How can I correctly calculate the number of minutes between these two dates in Javascript?

Okay - I am still very new to JavaScript, please be understanding and patient with me.
I have a script that returns two dates: one from a text file and the other is the system date. These two dates are displayed in this format:
Tue 29 Jun, 12:57 PM (from the text file) and
Mon Jul 26 2021, 11:47:21 PM (from the system date).
When I tried to subtract the two dates, I get this for output on the console:
NaN
I used the following code to try to get the difference between the two dates:
const diffInMilliseconds = Math.abs('computer_date' - 'slug_date');
console.log(diffInMilliseconds);
What does NaN mean?
What is the correct way to get the difference of two dates in JavaScript?
Do I need to convert the dates to another format before subtracting them?
***** Update ******
I am inserting the code that I have put together for trying to parse the date from a text file and compare to the system date.
const fs = require('fs');
//var str;
var slug_date = " ";
var computer_date = " ";
var diffInMinutes = 0;
fs.readFile('/home/xxxx/xxxx/xxxx/ocrtextparse.txt', 'utf8', function (err, data) {
var targetStr = 'Last Update:';
//var slug = targetStr.split(': ').pop(); // 2020
//var slug = targetStr.substring(targetStr.indexOf(':') + 1); // 01-2020
if (err) throw err;
if(data.includes(targetStr)){
console.log(data)
console.log(targetStr + " is present" + "\n")
//console.log(slug)
}
let arr = data.split(/\r?\n/);
arr.forEach((line, idx)=> {
if(line.includes(targetStr)){
console.log("Line " +(idx+1)+') '+ line + "\n");
//console.log(line.substring(line.indexOf(':')+ 2))
var slug = line.substring(line.indexOf(':')+ 2);
//console.log(slug)
slug_date = slug;
//console.log(slug_date)
}
})
//console.log(slug_date);
// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// log the date in the browser console
//console.log('date:', n);
// log the time in the browser console
//console.log('time:',time);
computer_date = (n + ", " + time);
//console.log(n + ", " + time);
console.log(computer_date);
console.log(slug_date);
//console.log("\n");
var file_date = Date.parse(slug_date);
//const diffInMilliseconds = Math.abs(computer_date - file_date);
//console.log(diffInMilliseconds);
console.log("\n");
//var date1 = new Date(slug_date);
var date2 = new Date(Date.now());
//var date3 = computer_date;
//diffInMinutes = Math.abs(Number(date2.getTime()) - Number(date1.getTime()))/60000;
//console.log(date1)
console.log(date2)
//console.log(date3)
//console.log(diffInMinutes)
var textFileDate = ((slug_date));
var appendYear = textFileDate.replace(',', ' ' + new Date().getFullYear()+',');
//var textFileDate = Date(appendYear);
console.log(computer_date);
console.log(appendYear);
diffInMinutes = Math.abs(Number(date2) - Number(appendYear))/60000;
console.log(diffInMinutes);
console.log(Number(date2));
console.log(Number(appendYear));
var a = new Date(appendYear);
var current = Date.now();
var diff = Math.abs(current - a);
var minutes = Math.floor((diff/1000)/60)
console.log("********")
console.log(minutes);
console.log("++++++++++++");
var dateZ = 'Tue 29 Jun, 12:57:00 PM';
console.log(dateZ);
});
I also have the text file that I am trying to . How can I attach it to my question?
You have quotes around your values. The quotes tell Javascript to interpret the data in the quote as a string. You are trying to subtract two strings, like "oranges" - "apples". Javascript doesn't understand this, which is why you are getting NaN.
NaN stands for Not a Number, and is what you get when you try to do something mathy that cannot you, such as divide by zero, or subtract things that can't be subtracted.
To fix it, remove the quotes:
const diffInMilliseconds = Math.abs(computer_date - slug_date);
Try this,
NaN stands for "Not a Number", if you try to perform mathematical operations on the data type other than number, you generally see this error.
text file refers to the year 2001, see the output below
var date1 = new Date('Tue 29 Jun, 12:57 PM');
var date2 = new Date(Date.now());
diffInMinutes = Math.abs(Number(date1.getTime()) - Number(date2.getTime()))/60000;
//output
10559347.2098
date1
Fri Jun 29 2001 12:57:00 GMT+0530 (India Standard Time)
date2
Tue Jul 27 2021 10:04:12 GMT+0530 (India Standard Time)
// If you are referring the date to 2021 from the text file, try this
var textFileDate = 'Tue 29 Jun, 12:57 PM';
var appendYear = textFileDate.replace(',', ' ' + new Date().getFullYear()+',');
var textFileDate = new Date(appendYear);
var sysDate = new Date(Date.now());
diffInMinutes = Math.abs(Number(textFileDate.getTime()) - Number(sysDate.getTime()))/60000;
//output
40164.49135
textFileDate
Tue Jun 29 2021 12:57:00 GMT+0530 (India Standard Time)
sysDate
Tue Jul 27 2021 10:21:29 GMT+0530 (India Standard Time)
The simplest would be to use Date.parse():
var origin_unix = Date.parse('Tue 29 Jun, 12:57 PM');
var current_unix = Date.now();
console.log( "Difference in Milliseconds: " + (current_unix - origin_unix) );
You may want to double-check that date from the text file, though, as there is no year.
First substract two dates using Math.abs() gives you the result in milliseconds. dividing the result by 1000 gives you the seconds, divide that by 60 gives you the number of minutes.
var a = new Date('Tue 29 june 2021, 12:57 PM')
var current = Date.now();
var diff = Math.abs(current - a);
var minutes = Math.floor((diff/1000)/60)
console.log(minutes);

How to extract only a part of the string in angular / javascript

I am using time-picker to get the time :
<div class="timePicker-container" >
<md-time-picker
className="end-time"
enable-date="false"
(whenChange)="timeSelectionChanged($event)"
[disabled]="systemlogsform.value.range==='relativerange'">
</md-time-picker>
</div>
And timeSelectionChanged is as shown below:
public timeSelectionChanged(momentTime) {
console.log('momentTime', momentTime._d)
}
This contains the below data:
Tue Jun 15 2021 00:17:32 GMT+0530 (India Standard Time)
Now , how will I be able to get only the time part , i.e. 00:17:32 ?
You can convert into Date format and get hours , minutes and seconds from there.
getOnlyTime(dateTimeFormat)
{
let newFormat = new Date(dateTimeFormat);
let hr = newFormat .getHours();
let mins = newFormat .getMinutes();
let secs = newFormat .getSeconds();
let timeOnly = hr + ":" + mins + ":" + secs;
return timeOnly;
}
You can call the method to retrieve the time.
let timeFormat = getOnlyTime(momentTime._d);
console.log(timeFormat);
I am not sure what package you are using to convert into the required format, but if you are using 'moment.js' package, you can take a look at this website
Link to moment.js ==> https://momentjs.com/
What you want to do is something like this:
var myDate = "2017-08-30T14:24:03";
console.log(moment(myDate).format("HH:mm")); // 24 hour format
console.log(moment(myDate).format("hh:mm")); // 12 hour format
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
const dt = "Tue Jun 15 2021 00:17:32 GMT+0530 (India Standard Time)"
const d = new Date(dt).toLocaleTimeString(undefined, {
timeZone: 'Asia/Kolkata'
})
console.log(d)

Trouble converting dates string to YYYY-MM-DDTHH:MM:SS-HH:MM format

I have a start date that looks like this:
var startDate = "Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)";
And I am trying to get it formatted into this:
var endDate = "2014-06-30T00:00:00-04:00";
I have gotten it to semi-format correctly using the toISOString() method:
var formattedDate = new Date(startDate);
formattedDate = formattedDate.toISOString();
Which formats it into "2014-06-30T04:00:00.000Z". This is close to what I need, but I was wondering if there was built in method to format it into the '-04:00' format? Or do I need to split my string into parts and mend it back together in the right format?
Also I am working out of Google Apps Script, which is ES5, and am trying to avoid jQuery if possible.
Google Apps Script (GAS) has a built-in utility method you can leverage to format dates:
Utilities.formatDate()
Its based on Java's SimpleDateFormat class.
To format the date to meet your requirements the following should suffice:
var date = new Date("Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)");
var formattedDate = Utilities.formatDate(
date,
Session.getScriptTimeZone(),
"yyyy-MM-dd'T'HH:mm:ssXXX"
);
Note: You may need to set your script's timezone from the GAS GUI menu via:
File->Project Properties->Info
I completely agree with #JordanRunning 's comment.
Still, out of curiosity I quickly put together a way to get your desired format:
// two helper functions
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function getOffset(offset) {
if(offset<0) {
wminutes = 0 - offset;
var posneg = "-";
} else {
wminutes = offset;
var posneg = "+";
}
var hours = pad(Math.floor(wminutes/60));
var minutes = pad(wminutes % 60);
return posneg+hours+":"+minutes;
}
// the actual format function
Date.prototype.toMyFormat = function() {
var format = this.getUTCFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds());
timezoneOffset = getOffset(this.getTimezoneOffset());
format += timezoneOffset;
return format;
}
// usage:
console.log(new Date().toISOString());
// "2018-11-16T20:53:11.365Z"
console.log(new Date().toMyFormat());
// "2018-11-16T21:53:11-01:00"
You can just reformat the string. The format in the OP is consistent with the format specified for Date.prototype.toString in ECMAScript 2018, so you can even reformat that wiht the same function:
// Convert string in DDD MMM DD YYYY HH:mm:ss ZZ format to
// YYYY-MM-DDTHH:mm:ssZZ format
function formatDateString(s) {
var m = {Jan:'01',Feb:'02',Mar:'03',Apr:'04',May:'05',Jun:'06',
Jul:'07',Aug:'08',Sep:'09',Oct:'10',Nov:'11',Dec:'12'};
var b = s.split(' ');
return `${b[3]}-${m[b[1]]}-${b[2]}T${b[4]}${b[5].slice(-5,-2)}:${b[5].slice(-2)}`;
}
console.log(formatDateString("Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)"));
// Not recommended, but it will format any date where its
// toString method is consistent with ECMAScript 2018
console.log(formatDateString(new Date().toString()));

Convert Epoch time to human readable with specific timezone

To convert epoch dateTime to human readable , using a simple new date(1495159447834) will suffice.
The problem I'm encountering now is that for my hybrid application, if the user set the time-zone in his phone date time setting to lets say GMT +12:00 ,the human readable dateTime will be different from what I would want the user to have and I would want him/her to follow the server timezone.
Thus , how would I convert the epoch number to a specific given timezone in a human readable format.
I have tried example like:
var test= new Date('1495159447834 GMT+0800').toString();
and it returns me an Invalid Date.
If possible, I would want this without any libraries. I have looked through the answers here and I believe that I could not find any answers I'm looking for. If there is any previously answered question with the same topic, do let me know and I will close this question!
You can use offset to convert your current datetime to a specific timezone.
function convertEpochToSpecificTimezone(timeEpoch, offset){
var d = new Date(timeEpoch);
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); //This converts to UTC 00:00
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
// convertEpochToSpecificTimezone(1495159447834, +3)
The offset will be your specific timezone. Example: GMT +03:00, your offset is +3. If GMT -10:00, offset is -10
there are number of ways to convert between Epoch and Human readable format
//Convert epoch to human readable date
var myDate = new Date( 1533132667*1000);
document.write(myDate.toGMTString()+"<hr>"+myDate.toLocaleString());
//this will return Wed, 01 Aug 2018 14:11:07 GMT
//Convert human readable dates to epoch
var myDate = new Date("Wed Aug 01 2018 14:11:07 GMT");
var myEpoch = myDate.getTime()/1000.0;
// this will return 1533132667
For Reference: https://www.epochconverter.com/programming/#javascript
Edit#
added a JSFiddle here
This is old, but I did it this way:
function formatDate(date, includeTime) {
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'America/Los_Angeles',
timeZoneName: 'short',
});
const [
{ value: month },
,
{ value: day },
,
{ value: year },
,
{ value: hour },
,
{ value: minute },
,
{ value: dayPeriod },
,
{ value: timeZoneName },
] = dateTimeFormat.formatToParts(date);
if (includeTime) {
return `${day} ${month} ${year} • ${hour}:${minute}${dayPeriod.toLowerCase()} ${timeZoneName}`;
}
return `${day} ${month} ${year}`;
This will output the time of the given timezone.
For example, if I have an epoch time (unix timestamp) and if I'm in Argentina, the time should be displayed as 03:45 GMT -3 of June 2, but with this code, it will be displayed as the time that should be displayed for Los Angeles.
My requirement was to display time in Los Angeles timezone, even if I visit the page from Argentina.
set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to
the epoch
d.setUTCSeconds(utcSeconds);
Or you can use momentjs
moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')
or you can use this way
var dateVal ="/Date(1342709595000)/";
var date = new Date(parseFloat(dateVal.substr(6)));
document.write(
(date.getMonth() + 1) + "/" +
date.getDate() + "/" +
date.getFullYear() + " " +
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds()
);

Javascript convert string to date format yyyy-MM-dd

I have a string which is in the format "05-01-2016" when i run the below code in chrome i get the correct output
var fromDate = new Date(searchOpts.RunDateFrom);
fromDate.format("yyyy-MM-dd");
output = "2016/05/01"
However, when this code is execute inside my js file i get this output
Sun May 01 2016 00:00:00 GMT+0530 (India Standard Time)
How do i prevent this? I need to pass the date in this format "2016-05-01" to solr
formattedDate = fromDate.getFullYear() + "-" + (fromDate.getMonth()+1) + "-" + fromDate.getDate()
If you just need the string
var year = fromDate.getFullYear();
var month = fromDate.getMonth() < 10 ? '0'+ fromDate.getMonth()+1 : fromDate.getMonth()+1
var date = fromDate.getDate() < 10 ? '0'+ fromDate.getDate(): fromDate.getDate()

Categories

Resources