I've written a function that will get the first line of an "Activity Array" because it holds the timestamp within the response.
That timestamp looks like this: 20220714.1757
The function below will output: 7/14/2022 12:57:00 PM
This is great and exactly what I wanted; however, I feel like my code is bloated, dirty, and inefficient. Is there an efficient way to write this function? I'm self-taught so I welcome any materials or references to learn more.
function get_timestamp(activityArray) {
let timestampBlock = activityArray[0];
let timestamp_array = timestampBlock.split(".");
let dateBlock = timestamp_array[0];
let timeBlock = timestamp_array[1];
let date_array = dateBlock.split("");
let year = date_array[0] date_array[1] date_array[2] date_array[3];
let month = date_array[4] date_array[5];
let day = date_array[6] date_array[7];
let date = year "-" month "-" day;
let time_array = timeBlock.split("");
let hour = time_array[0] time_array[1];
let minute = time_array[2] time_array[3];
let time = new Date(date "T" hour ":" minute "Z");
console.log(date "T" hour ":" minute "Z")
let formatted_time = time.toLocaleString();
let formatted_time_array = formatted_time.split(",");
let timestamp = formatted_time_array[0] " " formatted_time_array[1];
return timestamp;
}
console.log(get_timestamp(["20220714.1757"]));
CodePudding user response:
You can extract the date parts nicely with a regular expression. Then you can feed those as separate arguments to Date.UTC
, so you avoid string parsing. Only have to take care to make the month number zero-based:
function get_timestamp(str) {
return new Date(Date.UTC(
...str.match(/^....|\d\d/g).map((p, i) => p - !--i)
)).toLocaleString('en-US').replace(",", "");
}
console.log(get_timestamp('20220714.1757'));
CodePudding user response:
One thing that cleans up code is to put the params of recurring operations into data. Here, fields
describes where to expect elements of the date in the input string.
You may have some other reason to convert to a JS date and then format as an ISO string, then manipulate that string, but the trip seems circuitous. Here, we just interpolate the captured date elements into a new string.
(side note: your example input of 17:57 probably means 5:57 PM using a 12 hour clock -- not 12:57 as the OP suggests)
function get_timestamp(str) {
const fields = [
{ key: 'year', start: 0, end: 4 },
{ key: 'month', start: 4, end: 6 },
{ key: 'day', start: 6, end: 8 },
{ key: 'hour', start: 9, end: 11 },
{ key: 'minute', start: 11, end: 13 }
];
// produces { year: '2022', month: '07', ...
const d = fields.reduce((acc, el) => {
acc[el.key] = str.slice(el.start, el.end);
return acc;
}, {})
// convert to 12-hour clock
d.ampm = d.hour > 12 ? 'PM' : 'AM';
if (d.ampm === 'PM') d.hour -= 12;
// format using string interpolation
return `${d.month}/${d.day}/${d.year} ${d.hour}:${d.minute}:00 ${d.ampm}`
}
const activityArray = ['20220714.1757']
console.log(get_timestamp(activityArray[0]))
CodePudding user response:
function convert_timestamp(timestamp) {
function convert_timestamp(timestamp) {
const hour = parseInt(timestamp.slice(9, 11)) 2;
return `${timestamp.slice(6, 8)}/${timestamp.slice(4, 6)}/${timestamp.slice(0, 4)} ${hour > 24 ? (hour - 24).toString().padStart(2, "0") : hour.toString().padStart(2, "0")}:${timestamp.slice(11, 13)}:00`
}
console.log(convert_timestamp("20220714.2357")) // 14/07/2022 01:57:00
}
Simple one liner.