How to convert this date into actual date - javascript

So this is a new one to me. I've been working with this api and they returned a date in json format that looks like this
{
DateAdd: "/Date(1582936941390-0600)/"
}
not exactly sure how to convert this to a datetime like in the format below so I can actually do something with it.
2020-03-13 23:08:00
i have never seen this date format before! Thanks

Use moment.js to convert the date format
var data = {
DateAdd: "/Date(1582936941390-0600)/"
}
var datam = moment(data.DateAdd)
console.log(datam.format("YYYY-MM-DD HH:mm:ss")) // 2020-02-29 07:42:21
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>

If you don't care about the timezone, you can just cut the timestamp out of that string:
const dateString = data.DateAdd;
const date = new Date(Number(dateString.match(/\d+/)[0]));

You can convert date into desired format by Javascript date object.
let addZero = (i) => {
if (i < 10) {
i = "0" + i;
}
return i;
}
let formatDate = (date) => {
let year = date.getFullYear(),
month = addZero(date.getMonth() + 1),
day = addZero(date.getDate() + 1),
hours = addZero(date.getHours() + 1),
minutes = addZero(date.getMinutes() + 1),
seconds = addZero(date.getSeconds() + 1);
let dateArr = [year, month, day];
let timeArr = [hours, minutes, seconds];
let result = dateArr.join('-').concat(" ", timeArr.join(':'));
return result;
}
let inputString = "/Date(1582936941390-0600)/";
let inputData = new Date(Number(inputString.match(/\d+/)[0]));
console.log(formatDate(inputData));
Please read more about Javascript date object

Related

convert string to time javascript in order to have ability to sort it

I need to convert string of format "14.12.22 15:17" to date in order to sort it by seconds. thank you in advance
const toTimestamp = (strDate) => {
const parsedDate = strDate.split(".");
const b = parsedDate[2].split(" ");
const string = `20${b[0]}-${parsedDate[0]}-${parsedDate[1]}T${b[1]}:00`;
const date = new Date(string).getTime();
console.log(string);
return date;
};
toTimestamp('4.12.22 15:17');
You want to use Date.parse() after converting the string to ISO 8601 format:
const datestrings = ["14.12.22 15:17", "14.12.22 15:16", "12.12.22 22:22"]
const toTimestamp = (strDate) => {
const parts = strDate.split(" ")
const d = parts[0].split(".");
const t = parts[1]
const string = `20${d[2]}-${d[1]}-${d[0]}T${t}`;
const date = Date.parse(string);
console.log(string, date);
return date;
}
const dateTimes = []
datestrings.forEach(d => dateTimes.push(toTimestamp(d)))
dateTimes.sort()
console.log(dateTimes)
var t = "14.12.22 15:17"
var ts = t.split(" ");
var tss = ts[0].split(".")
var tsss = []
tsss.push(tss[1] + ".")
tsss.push(tss[0] + ".")
tsss.push(tss[2] + " ")
tsss.push(ts[1])
tsss.join();
var d = new Date(tsss);
console.log(d.getTime()/1000);
You can use third-party libraries for parsing the date, e.g., moment.js is one of the famous ones.
Your code can simplified as
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
const momentDate = moment('14.12.22 15:17', 'YY.MM.DD HH:mm');
console.log(momentDate.toDate());
</script>
</body>
</html>
Once you have the object you can easily sort on the date object.
Using dayjs:
const dayjs = require('dayjs')
const customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)
const toTimestamp = (strDate) => {
return dayjs(strDate, 'DD.MM.YY HH:mm').unix()
}
I'm not sure why you are doing all the parsing and re-assembling into an ISO format manually? Without pulling in any libraries like suggested by #Manish Rawat you could do the parsing with a regex, might make it a bit more readable:
// as pointed out in the comments, this doesn't work as expected
// it will interpret the '4' as the month...
//console.log((new Date('4.12.22 15:17')).toISOString())
const toDate = function(str) {
const rex = /(?<day>\d+).(?<month>\d+).(?<year>\d+)\s+(?<hours>\d+):(?<minutes>\d+):?(?<seconds>\d+)?/;
const { day, month, year, hours, minutes, seconds } = (str.match(rex))?.groups || {
day: 0,
month: 0,
year: 0,
hours: 0,
minutes: 0,
seconds: 0
};
// console.log(str.match(rex)?.groups, year, month, day, hours, minutes, seconds);
return new Date(`20${year}-${month}-${day} ${hours}:${minutes}${seconds ? ':' + seconds : ''}`);
};
console.log(toDate('4.12.22 15:17'), toDate('4.12.22 15:17').getTime());
also, from there, what kind of sort are you planning to do? string based i assume? why not convert those dates to actual unix timestamps, e.g. number of seconds and compare those, so you won't have to deal with "weird" javascript string sorting things that might not yield the sort you are expecting?

Getting date range based on date and hour

I am trying to get individual dates ("2022-10-10") and hours ("2022-10-10T09") between an interval in UTC. I could get the individual dates by the following -
function getDatesInRange(startDate, endDate) {
const date = new Date(startDate.getTime());
const dates = [];
while (date <= endDate) {
const day = new Date(date).toISOString().split(':')[0].split('T')[0];
dates.push(day);
date.setDate(date.getDate() + 1);
}
return dates;
}
console.log(getDatesInRange(new Date('2022-10-10T20:50:59.938Z'), new Date('2022-10-15T23:50:59.938Z')));
Hence, the above returns - ["2022-10-10", "2022-10-11", "2022-10-12", "2022-10-13", "2022-10-14", "2022-10-15"]
I also want to return the hours of the start and end date and the rest should be dates. So i want to get in return - ["2022-10-10T20", "2022-10-10T21", "2022-10-10T22", "2022-10-10T23" "2022-10-11", "2022-10-12", "2022-10-13", "2022-10-14", "2022-10-15T00", "2022-10-15T01"]
Here is what i have as of now -
function getHoursInRange(startDate, endDate) {
let startDatePlusOne = new Date(startDate);
startDatePlusOne.setDate(startDatePlusOne.getDate() + 1);
let endDateMinusOne = new Date(endDate);
endDateMinusOne.setDate(endDateMinusOne.getDate() - 1);
const date = new Date(startDate.getTime());
console.log("Start date :", date);
let dates = getDatesInRange(startDatePlusOne, endDateMinusOne);
console.log("Only days : ", dates);
startDatePlusOne.setHours(0);
while (date < startDatePlusOne) {
const day = new Date(date).toISOString().split(':')[0];
dates.push(day);
date.setHours(date.getHours() + 1);
}
endDateMinusOne.setHours(23);
const edate = endDateMinusOne.getTime();
while (edate < endDate) {
const day = new Date(edate).toISOString().split(':')[0];
dates.push(day);
date.setHours(date.getHours() + 1);
}
return dates
}
For this use case, i am getting the days back excluding the start and end dates. But for getting each hour of start and end date it gets stuck somehow. Somehow i feel there is a better way to do this. Any ideas ?
You can do it a simpler way by incrementing the timestamp by 30 minutes at a time, and keeping a note of all non-duplicate hour strings and date strings:
function getDatesInRange(startDate, endDate) {
let h = new Set(), d = new Set(), t = [];
for(let i=startDate.getTime(); i<endDate.getTime(); i+=1000*1800) t.push(i);
[...t, endDate.getTime()].forEach(i=>{
let s = new Date(i).toISOString();
[[s.split(':')[0], h], [s.split('T')[0], d]].forEach(([s,r])=>r.add(s));
});
let firstDate = [...d.values()][0], lastDate = [...d.values()].pop();
return d.size===1 ? [...h.values()] : [
...[...h.values()].filter(v=>v.startsWith(firstDate)),
...[...d.values()].filter(v=>v!==firstDate && v!==lastDate),
...[...h.values()].filter(v=>v.startsWith(lastDate))];
}
console.log(getDatesInRange(
new Date('2022-10-10T20:50:59.938Z'), new Date('2022-10-15T23:50:59.938Z')));
dateRange constructs an array of Date objects corresponding to the supplied range, inclusive.
dayToString takes a date and creates an array of strings, one for each hour of the day between the specified UTC hour range, inclusive.
dateRangeToStrings accepts an array of dates and constructs an array of strings according to the rules laid-out in the question.
const twoDigit = (n) => String(n).padStart(2, '0')
const toISODateString = (date) => `${date.getUTCFullYear()}-${twoDigit(date.getUTCMonth() + 1)}-${twoDigit(date.getUTCDate())}`
const dateRange = (start, end, curr = new Date(start)) => {
const dates = []
while (curr <= end) {
dates.push(new Date(Date.UTC(curr.getUTCFullYear(), curr.getUTCMonth(), curr.getUTCDate())))
curr.setUTCDate(curr.getUTCDate() + 1)
}
return dates
}
const dayToString = (date, startUTCHour = 0, endUTCHour = 23) =>
Object.keys([...Array(24)])
.slice(startUTCHour, endUTCHour + 1)
.map((h)=>`${toISODateString(date)}T${twoDigit(h)}`)
const dateRangeToStrings = (arr, startUTCHour, endUTCHour) => {
const beginning = dayToString(arr[0], startUTCHour)
const middle = arr.slice(1, -1).map(toISODateString)
const end = dayToString(arr[arr.length - 1], 0, endUTCHour)
return beginning.concat(middle, end)
}
const getDatesInRange = (start, end) =>
dateRangeToStrings(dateRange(start, end),
start.getUTCHours(),
end.getUTCHours())
console.log(getDatesInRange(new Date('2022-10-10T20:50:59.938Z'),
new Date('2022-10-15T23:50:59.938Z')))

Javascript: formatting a date [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I want to the current date/time formatted in this format:
year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Currently I'm doing it as such. Is there a more elegant approach without the use of external libraries like moment.js?
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var milli = now.getMilliseconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
if(milli.toString().length == 1) {
var milli = '0'+milli;
}
var m_session_startTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Leverage template literals instead of concatenation and padStart() to fill leading zeros.
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const milli = String(now.getMilliseconds()).padStart(4, "0");
const m_session_startTime = `${year}-${month}-${day} ${hour}:${minute}:${second}:${milli}`;
console.log(m_session_startTime);
You could use moment.js, it really helps you with formatting dates.
console.log(moment().format('YYYY-MMMM-DD h:mm:ss:SSS'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
This command does the job pretty well. moment() is a date object, when there are no arguments given like in this example it takes the current time but you can also use moment("2018-12-4") for specific dates.
You can then format the date according to your need,
YYYY is the full year (2018)
MMMM is the full month name (July)
(you can also use MMM for the short version of the month name)
DD is the day as a number (24)
(you can also use dddd for the full name of the day or ddd for the short name)
h is the hour as number (22)
mm is the minute as a number (23)
ss is the second as a number (as an example 22)
SSS is the millisecond as a number (example 245)
Try this?
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
console.log(jsonDate);
> 2018-07-24 20:32:06:435
Alternatively, if you want to split the entire thing into substrings:
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
let dateTime = jsonDate.split(" ");
let dt = dateTime[0].split("-");
let tt = dateTime[1].split(":");
let year = dt[0];
let month = dt[1];
let day = dt[2];
let hour = tt[0];
let minute = tt[1];
let second = tt[2];
let mili = tt[3];
console.log(jsonDate);
console.log(dateTime[0]);
console.log(dateTime[1]);
console.log([year, month, day, hour, minute, second, mili].join("~"));
console.log("Date: " + [year, month, day].join("-") + " Time: " + [hour, minute, second, mili].join(":"));
> 2018-07-24 21:03:05:706
> 2018-07-24
> 21:03:05:706
> 2018~07~24~21~03~05~706
> Date: 2018-07-24 Time: 21:03:05:706
As you might have noticed from this response, I work with databases. I have heavy bash, javascript, php, sql, golang background.
Use a moment.js. Great library that is designed to exactly what you would like. You can use the .format option.
var now = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
$('#timeval').text(now);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current Time: <br>
<a id="timeval"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
https://momentjs.com/

Set last day of month on YYYYMM date format - Javascript

I've a variable that has value of date in YYYYMM format. For example:
var givenDate = "201704"
How can I find out the last day of the given month and append to it. For example,
//last day of 2017 04 (April) is 30th so append value to givenDate + lastDate;
//that will be 20170430
var newFullGivenDate = "20170430";
const date = "201704";
const year = parseInt(date.substring(0, 4));
const month= parseInt(date.substring(4, 6));
const lastDay = (new Date(year, month, 0)).getUTCDate();
const newFullGivenDate = date + lastDay;
console.log(newFullGivenDate);
var givenDate = "201704";
var month = givenDate.substring(4, givenDate.length); // retrieves 04
var year = givenDate.substring(0, 4); // retrieves 2017
var d = new Date(year, month, 0);
alert(d.getDate());
Reference: MDN
To achieve expected result, use below option
last day of month - new Date(year,month ,0)
var givenDate = "201704";
var currDate = new Date(givenDate.substr(0,3),givenDate.substr(4) ,0)
var newFullGivenDate = givenDate + currDate.getDate();
console.log(newFullGivenDate)
Codepen URL for reference - https://codepen.io/nagasai/pen/OmgZMW
I would break it down into two functions:
// Get last day from year and month
let lastDayOf = (year, month) => (new Date(year, month, 0)).getDate();
// Add last day to string only if input is correct
let addLastDay = (input) => {
// In case you pass number (201705) instead of string ("201705")
if (Number.isInteger(input)) input = input.toString();
// Check if input is in correct format - 6 digit string
if (typeof input !== "string" || !input.match(/^\d{6}$/)) {
return input; // You can implement desired behavour here. I just return what came
}
const year = input.substr(0, 4);
const month = input.substr(4, 2);
return input + lastDayOf(year, month);
}
// Tests
console.assert(addLastDay("201704"), "20170430");
console.assert(addLastDay("201702"), "20170228");
console.assert(addLastDay("201202"), "20120229");
console.assert(addLastDay(201705), "20170531");
console.assert(addLastDay(20170), 20170); // Wrong input
// Interactive example
document.getElementsByTagName('button')[0].addEventListener('click', () => {
let input = document.getElementsByTagName('input')[0];
input.value = addLastDay(input.value);
});
<input type="text" value="201704"><button>Calculate</button>
If you are using moment js you can yry this:
var date = moment(newFullGivenDate ).format('YYYYMMDD');
date = date.add(-1 * parseInt(date.format('DD')), 'days').add(1, 'months');

Convert date string into proper date in Javascript

I get an array with dates as string from the server, now I want to filter only day, month and year. How can I format the filter result to a certain date format?
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00', ...];
//wanted result: 2015-02-04 or 04.02.2015
You could convert your what's look to be an ISO Date format like this:
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
date.map(function(_d) {
var d = new Date(_d)
return d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDay()
}
// if you want to get fancy, you could throw in this function to pad the days and months:
var pad = function (n) {return n<10? '0'+n:''+n;}
var sorted = date.map(function(_d) {
var d = new Date(_d)
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDay())
})
console.log(sorted);
Date can take an argument of a string. Use a for loop to iterate through your list, and then make a new Date object for each one.
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00']
var dateObjects = [];
for (var i = 0; i<date.length; i++) {
d = new Date(date[i]);
dateObjects.push(d);
}
Or, in a single line:
var dateObjects = date.map( function (datestr) {return new Date(datestr)} );
Now, you can find the month, day, and year from one of these by the following methods:
var year = dateObjects[0].getFullYear(); // Gets the year
var month = dateObjects[0].getMonth()+1; // Gets the month (add 1 because it's zero-based)
var day = dateObjects[0].getDate(); // Gets the day of the month
dateObjects[0] is just an example that refers to the first date in the list.
So you can then get your output string like
var dateStrings = dateObjects.map(function (item) {
return item.getFullYear()+"-"+(item.getMonth()+1)+"-"+item.getDate();
})
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
var newdateobject = [];
$.each( date, function(key, e) {
var a = new Date(e);
newdateobject.push(a.getFullYear()+'-'+(a.getMonth()+1) +'-'+a.getDate());
});
IF the format you mentioned is consistent, then:
date.forEach(function(d) {
d = d.substring(0, 10);
})

Categories