moment.js not creating right date - javascript

I cant seem to figure out what the issue is I have a manual time enter function on my website where a user can enter a time and then I store it in the db..
So my function looks like this..
createTime() {
this.startTime = moment(`${this.hour}:${this.minute} ${this.timeOfDay}`, `HH:mm a`).utc();
}
so I typed in 5:45pm
now when I console.log() the created moment I get this...
so its the right utc time but it says its in AUS TIME
then when I get the time back from the server and then try to convert it back to local time like so..
fixTime(momentObject: moment.Moment) {
return moment(momentObject).local().format('hh:mm A');
}
I get 4:45am
I can not figure out what the issue is.. how can I fix this?

fixTime(momentObject: moment.Moment) {
var testDateUtc = moment.utc(momentObject);
var localDate = moment(testDateUtc).local();
return localDate.format('hh:mm A');
}
you must Create a moment object and set the UTC flag to true on the object and Create a localized moment object converted from the original moment object and finally Return a formatted string from the localized moment
object.
See: http://momentjs.com/docs/#/manipulating/local/

Related

Return the date format for date without moment.js

I can't figure out how to build a function that does this
INPUT: dateToDateFormat('16/07/2022') -> OUTPUT: DD/MM/YYYY
INPUT: dateToDateFormat('07/16/2022') -> OUTPUT: MM/DD/YYYY
The input dates will be already formatted by .toLocaleString function
Edit:
I think I was not precise enough with the output, it should literally output MM/DD/YYYY as a string, not the actual date value
A) First of all, your desired date string conversion seems to be easy (solution below) without using any package/overhead.
B) However, if you need to process it further as a JS Date Object, things become more difficult. In this case, I like to provide some useful code snippets at least which might help you depending on your usecase is or what you are aiming for.
A) CONVERSION
Seems you need a simple swap of day and month in your date string?
In this case, you do not need to install and import the overhead of a package such as date-fns, moment or day.js.
You can use the following function:
const date1 = "16/07/2022"
const date2 = "07/16/2022"
const dateToDateFormat = (date) => {
const obj = date.split(/\//);
return `${obj[1]}/${obj[0]}/${obj[2]}`;
};
console.log("New date1:", dateToDateFormat(date1))
console.log("New date2:", dateToDateFormat(date2))
B) STRING TO DATE
Are you using your date results to simply render it as string in the frontend? In this case, the following part might be less relevant.
However, in case of processing them by using a JS Date Object, you should be aware of the following. Unfortunately, you will not be able to convert all of your desired date results/formats, here in this case date strings "16/07/2022" & "07/16/2022", with native or common JS methods to JS Date Objects in an easy way due to my understanding. Check and run the following code snippet to see what I mean:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
console.log("dateFormat1", dateFormat1);
console.log("dateFormat2", dateFormat2);
dateFormat2 with its leading 16 results in an 'invalid date'. You can receive more details about this topic in Mozilla's documentation. Furthermore, dateFormat1 can be converted to a valid date format but the result is not correct as the day is the 15th and not 16th. This is because JS works with arrays in this case and they are zero-based. This means that JavaScript starts counting from zero when it indexes an array (... without going into further details).
CHECK VALIDITY
In general, if you need to further process a date string, here "16/07/2022" or "07/16/2022", by converting it to a JS Date Object, you can in any case check if you succeed and a simple conversion with JS methods provides a valid Date format with the following function. At least you have kind of a control over the 'invalid date' problem:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
function isDateValidFormat(date) {
return date instanceof Date && !isNaN(date);
}
console.log("JS Date Object?", isDateValidFormat(dateFormat1));
console.log("JS Date Object?", isDateValidFormat(dateFormat2));
Now, what is the benefit? You can use this function for further processing of your date format depending on what you need it for. As I said, it will not help us too much as we still can have valid date formats but with a falsy output (15th instead of 16th).
CONVERT TO DATE OBJECT BY KNOWING THE FORMAT
The following function converts any of your provided kinds of dates ("MM/DD/YYYY" or "DD/MM/YYYY") to a valid JS Date Object and - at the same time - a correct date. However, drawback is that it assumes to know what kind of input is used; "MM/DD/YYYY" or "DD/MM/YYYY". The dilemma is, that this information is crucial. For example, JS does not know if, for example, "07/12/2022" is "MM/DD/YYYY" or "DD/MM/YYYY". It would return a wrong result.
const newDate1 = "07/16/2022"
const newDate2 = "16/07/2022"
function convertToValidDateObject(date, inputFormat) {
const obj = date.split(/\//);
const obj0 = Number(obj[0])
const obj1 = Number(obj[1])
const obj2 = obj[2]
//
// CHECK INPUT FORMAT
if (inputFormat === "MM/DD/YYYY") {
return new Date(obj2, obj0-1, obj1+1);
} else if (inputFormat === "DD/MM/YYYY") {
return new Date(obj2, obj1-1, obj0+1);
} else {
return "ERROR! Check, if your input is valid!"
}
}
console.log("newDate1:", convertToValidDateObject(newDate1, "MM/DD/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "DD/MM/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "MM/YYYY"))
If the wrong format is provided as a second argument, an error is provided in the console. In practise I suggest you to use a try-catch block ( I tried here, but it does not work here in this stackoverflow editor).
I wish you good luck. Hope these information can help you.

c# datetime utc string and the z when using in javascript

I am getting a date from my api and the format i get is "2019-04-17T15:04:28"
the date is UTC.
Should the date i get back have the Z at the end or doesn't it matter. Javascript date function will display incorrect if the Z is not there wont it?
Thanks #Esko thanks i think for me the confusion is that in .net core if you change the json serializer options in startup.cs by the following:
AddJsonOptions(opt =>{
opt.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
});
the tool tip in visual studio says yet it doesn't put the Z on and the documentation also doesn't show the Z (https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm)
Instead i am going to try and set a different option
opt.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
If you know the timezone to be constant, you can always just append +0Z00 to your datestring. For example, if the server serializes time into CEST, turn "2019-04-17T15:04:28" into "2019-04-17T15:04:28+0100"
Parsing "2019-04-17T15:04:28" in new Date will parse it as if it's in your local timezone - the meaning of this string depends on what timezone it's parsed in.
Parsing "2019-04-17T15:04:28Z" will parse it in GMT - meaning that no matter what system parses it, it will always refer to the same time.
In other words, "2019-04-17T15:04:28" as a timestamp is ambiguous unless you know the timezone it was recorded in.
I had the similar problem and I found the answer
In my case the DateTime was with Kind Unspecified, in this case the JsonConvert hasn't enough information to add the Z in the end.
You have several options:
Convert it to UTC with ToUniversalTime method
If you're sure you're working with UTC you can add it to general JsonOptions like this:
JsonConvert.DefaultSettings = (() =>
{
return new JsonSerializerSettings
{
Converters = new List<JsonConverter>() {new IsoDateTimeConverter { DateTimeStyles= System.Globalization.DateTimeStyles.AssumeUniversal } }
};
});
if you just want to add the Kind=UTC to current Unspecified Date, you can always write isoConverter like this:
JsonSerializerSettings
{
Converters = new List<JsonConverter>() { new CustomIsoDateTimeConverter() }
};
Where the class will look like this:
public class CustomIsoDateTimeConverter : IsoDateTimeConverter
{
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is DateTime dateTime && dateTime.Kind == DateTimeKind.Unspecified)
value = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
base.WriteJson(writer, value, serializer);
}
}

Moment js split time string

Am using moment JS to get the current time. Based on that time I need execute search operation in my elastic search database.
My database entry is like this way :
"message_date": "2014-03-20T09:17:40.482Z"
Moment code to get current time is like this way :
var m = moment();
var testResult = m.toJSON();
// It outputs : 2014-03-20T09:17:40.482Z
My problem is I don't want to include that seconds filed in my database query. I want to search only up to minute field i.e 2014-03-20T09:17. I can split the moment date to get the expected format. But i know its not the way to do that. Please help me to get the expected time format in moment JS way. Thanks
Try:
var testResult = m.format('YYYY-MM-DD[T]HH:mm');
If you want to get the time in a particular timezone:
var m = moment().zone("+05:30");
var testResult = m.format('YYYY-MM-DD[T]HH:mm');

Compare Current Date and Time to input of type DateTime

I have googled a bit and could not find an answer. So here is my situation.
I have an input of type dateTime. I want to compare the value picked (mobile app for blackberry) to the current date and time. if the selected date is in the future (bigger than date now) I have to show a simple error message. This is all done when the user tries to save the data.
I have tried code like this, but was unsucessfull.
var dateOfIncident = $('#AccidentDetailsDate').val();
var dateNow = Date.now();
if(dateNow > dateOfIncident)
{
// do my stuffs :)
}
This does not work... It passes that validation. I am very new to javascript myself. Any help would be greatly appreciated. I googled and could not find a solution that does not use anything fancy. I need to do it in javascript.
Thanks in advance.
Try this:
var dateOfIncident = new Date($('#AccidentDetailsDate').val()); // or Date.parse(...)
var dateNow = new Date(); // or Date.now()
if(dateNow > dateOfIncident)
{
// do your stuffs...
}
However, if this works may depend on what format your date-string is! You may want to consider this post as well.

javascript/python time processing fails in chrome

I am writing a timer web app,which records start time and stop time.It uses javascript,jquery1.4.2 for the front end and python for backend code.When a start button is clicked ,start time is saved in a javascript variable.when the button is clicked again, stop time is saved in another variable.These values are passed as hidden parameters to the python code which gets the start,stop values from django's request parameter.
I expect the start/stop parameters values to be in the following format
"07:16:03 PM"
so that it can be parsed using '%I:%M:%S %p'format string.
I am getting this correctly in mozilla firefox.But when I use chrome,I only get
"19:16:03"
This causes value error when I try to parse it with the above format string.
import time
...
def process_input(request,...):
start_time=request.POST[u'timerstarted']
...
fmtstr='%I:%M:%S %p'
start_time_list = list(time.strptime(start_time,fmtstr)[3:6])
I tried putting alert('start time set as'+start_time) in javascript to find what values are set in the page's hiddenfields
With firefox ,I got
start time set as08:03:09 PM
stop time set as08:03:43 PM
but with chrome
start time set as20:04:21
stop time set as20:04:32
My knowledge of javascript,jquery is minimal.Why is the script behaving differently in these two browsers? Below is the javascript snippet
$(document).ready(function(){
var changeBtnStatus=function(){
var timebtnvalue=$('#timebtn').attr("value");
if (timebtnvalue =="start"){
...
var start_date=new Date();
var str_time=start_date.toLocaleTimeString();
var timerstartedfield =$('#timerstarted');
timerstartedfield.attr("value",str_time);
alert('start time set as'+str_time);
}
else if (timebtnvalue=="stop"){
...
var stop_date=new Date();
var stp_time=stop_date.toLocaleTimeString();
var timerstoppedfield =$('#timerstopped');
timerstoppedfield.attr("value",stp_time);
alert('stop time set as'+stp_time);
}
};
var timerBtnClicked=function(){
...
changeBtnStatus();
};
$('#timebtn').click(timerBtnClicked);
...
}
);
You don't want the string of the time in locale, using the toString method you can provide your own format, or use toUTCString().
toLocaleTimeString is especially meant to display the time as the user is used to, you want it in a set format.
So instead of start_date.toLocaleTimeString(), you want to use start_date.toUTCString().
Why format the time in JavaScript and parse in Python, and even submit yourself to the confusion of different locales?
Try using Date.getTime insteam:
start_time = (new Date).getTime();
stop_time = (new Date).getTime();
This gets you the time in milliseconds since the epoch, which should always be stable.

Categories