I'm trying to add a string comma (,) between the date and time formats. Can someone kindly show how I can achieve this for the following code? I thought it might be as simple as adding a comma in between, but unfortunately this doesn't seem to be working for me.
Example:
14 JUN 21, 18:55:03
Line 1:
return handleFileType(req, res, user, dataFile, email, origin, previewSubject, finalFormatDate.format('DD MMM YY HH:mm:ss')
Line 2:
const date = moment.unix(dateToUnixTimestamp(memo.createdAt)).format('DD MMM YY HH:mm:ss');
The reason I published both these lines, is because I'm not sure if anything can vary between them.
The format method parses a format string and replaces tokens with values from the date. Non–tokens are kept as–is, so just add the comma where you want it in the format string:
format('DD MMM YY, HH:mm:ss')
let date1 = moment().format('DD MMM YY HH:mm:ss');
console.log(date1)
let date2 = moment().format('DD MMM YY, HH:mm:ss');
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
If you prefer to avoid using moment.js, it is also possible with native Date javascript class methods:
let a = new Date();
let timeStr = a.toLocaleTimeString('en-GB')
let dateStr = a.toLocaleDateString('en-GB')
let timeDateStr = dateStr + ', ' + timeStr;
console.log(timeDateStr);
Related
In my country, today is 12/15/2022, I'm from Asia which is gmt+8.
Basically I want my date to be 2022-12-15T00:00:00.000Z instead of showing 2022-12-14T16:00:00.000Z.
here is the code:
const today = new Date().toLocaleDateString();
console.log(new Date(today));
But I really want it to be exact like this
2022-12-15T00:00:00.000Z
is it possible without using logic "add +8 hours"?
One way is to run your code in UTC zone so that you don't accidentally create dates in different time zones. You can set TZ='UTC' environment variable for this.
Otherwise you can create the date like this.
const today = new Date().setUTCHours(0, 0, 0, 0); // note 'today' is a number now
> console.log(new Date(today))
2022-12-15T00:00:00.000Z
you can force your time zone like this
console.log(new Date(new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'})))
Edit:
changed toLocaleString to toLocaleDateString
this should meet your needs now
You can first convert the date to a local date string, then parse the year, month and day from it to construct the local ISO zero date string:
const localDate = new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'});
console.log('localDate:', localDate);
let m = localDate.match(/(\d+)\/(\d+)\/(\d+)/);
let localZero = m[3] + '-' + m[1] + '-' + m[2] + 'T00:00:00.000Z';
console.log('localZero:', localZero);
Output:
localDate: 12/15/2022
localZero: 2022-12-15T00:00:00.000Z
Suppose I've got a date in string format, such as "2021-07-19". How can I subtract x days from this date that is represented as a string?
I have tried to convert the string into a date first, then subtract the number of days, and convert back to a string, but that doesn't work.
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = previousDayDate.toString()
The ultimate result should be "2021-07-18". Instead, I get the date as a full string: Sun Jul 18 2021 01:00:00 GMT+0100 (British Summer Time)
The reason you get the wrong date is that "2021-07-19" is parsed by built–in parsers as UTC, but all the other methods you're using are local, so you appear to get the wrong date or time. Other than that, your algorithm is sound. Just parse the string as local to being with:
// Parse string in YYYY-MM-DD format as local
function parseISOLocal(s) {
let [Y, M, D] = s.split(/\W/);
return new Date(Y, M-1, D);
}
console.log(parseISOLocal('2021-07-20').toString());
This is a very common issue.
Note, the snippet below didn't work in my locale until I changed the input date to YYYY-MM-DD.
// const dateString = "2021-19-07" - your format
const dateString = "2021-07-19" // format testable in my locale
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = `${previousDayDate.getFullYear()}-${('0' + (previousDayDate.getMonth()+1)).slice(-2)}-${('0' + previousDayDate.getDate()).slice(-2)}`;
console.log(previousDayDateString)
Using Moment.js
const dateString = moment("2021-07-19", "YYYY-MM-DD").startOf("day")
const previousDayDateString = dateString.subtract(1, "days").format("YYYY-MM-DD");
Thank you all for the suggestions. I followed the same convention as Spencer's comment above (How to format a JavaScript date?) by doing:
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayString = previousDayDate.toLocaleDateString("en-CA").split(",")[0]
console.log(previousDayString)
I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.
i am trying to convert a string into date type.i am giving the string value to new date().
but it's returning next day date instead of date which i am trying to convert.
var endDate = new Date("2017-03-23T23:59:59.000Z");
//end date value is now ------ Fri Mar 24 2017 05:29:59 GMT+0530 (India Standard Time).
Please suggest me how can get correct date in the format MM/DD/YYYY
This hack can help you,
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
it will give you,
"2017-03-23T23:59:59.000Z"
Further if you want to convert it to DD/MM/YYYY then you can use native javascript or lib like moment for that,
This simpile js will help to convert it to any format.
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
var d1 = endDate.split('T'); //spliting date from T
var d2 = d1[0].split('-'); //getting date part
console.log('yyyy/MM/dd', d2[0] + "/" + d2[1] + "/" + d2[2]) //YYYY/MM/DD
console.log("DD/MM/YYYY", d2[2] + "/" + d2[1] + "/" + d2[0])
jsfiddle link
if your time is in IST use below
var endDate = new Date("2017-03-23T23:59:59.00+0530");
If you check dates, you will see that your dates differs in 5h 30 mins, that is same as your date saying GMT +0530. Your original date has .000Z that is time zone of GMT +0.
Make sure you use same time zone when working with date.
Try using Date.UTC('your date')
JavaScript Date objects carry no timezone information. The only reason you saw a non-UTC date is that the browser chooses by default to display dates as local time in the console. If you don't care about the date object aligning with the exact instant in local time, you can use the following format function to turn it into MM/DD/YYYY format:
function format (date) {
var mm = ('0' + (date.getUTCMonth() + 1)).slice(-2)
var dd = ('0' + date.getUTCDate()).slice(-2)
var yyyy = date.getUTCFullYear()
return mm + '/' + dd + '/' + yyyy
}
var endDate = new Date("2017-03-23T23:59:59.000Z")
console.log(endDate.toISOString())
console.log(format(endDate))
(Credit to Ranj for posting an answer using Date#toISOString before mine.)
I have created the solution over here please find below link
https://www.w3schools.com/code/tryit.asp?filename=FD0YSGRMB59W
I have this string in Javascript
"/Date(1317772800000)/"
and I'd like to display it as a meaningful date in my page. Currently, when I output the variable that contains this date I get the following displayed on my page
/Date(1317772800000)/
What I'd like is to display this in the format DD MM YYYY like so
10 05 2011
How is this possible?
try this
var date = new Date(Number.parseFloat('/Date(1317772800000)/'.substring(6)));
var newdate = date.getMonth() +' ' +date.getDate() +' ' +date.getFullYear()
If you have your date in a string provided then first you need to extract the number:
var strDate = "/Date(1317772800000)/";
var dateInt = strDate.replace("/Date(","").replace(")/","");
var date = new Date(parseInt(dateInt))
This gives you a JavaScript date object that you can do pretty much a lot with, if you want simple check just execute:
alert(date)
Try using moment.js i.e.:
moment().format('MMMM Do YYYY, h:mm:ss a')
Then you can do:
moment(1317772800000).format("MMM Do YY");
Try this
unixtime = 1317772800000;
var newDate = new Date();
newDate.setTime(unixtime);
dateString = newDate.toUTCString();
alert(dateString);
DEMO